Android將Glide動(dòng)態(tài)加載不同大小的圖片切圓角與圓形的方法
Glide加載動(dòng)態(tài)圖片
首先我們先要去依賴一個(gè)githup:bumptech:glide:glide:3.7.0包;
使用Glide結(jié)合列表的樣式進(jìn)行圖片加載:
1) 如果使用的是ListView,可以直接在Adapter的getView方法中使用:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (null == convertView) {
//.....
}
Glide
.with(context)
.load(imageUrls[position])
.into(holder.imageView);
return convertView;
}
2) 如果使用的是RecyclerView,可以在Adapter的onBindViewHolder方法中使用:
@Override
public void onBindViewHolder(RVViewHolder holder, int position) {
Glide.with(MainActivity.this)
.load(args[position])
.into(holder.imageView);
}
3) 當(dāng)加載網(wǎng)絡(luò)圖片時(shí),由于加載過程中圖片未能及時(shí)顯示,此時(shí)可能需要設(shè)置等待時(shí)的圖片,通過placeHolder()方法:
Glide .with(context) .load(UsageExampleListViewAdapter.eatFoodyImages[0]) .placeholder(R.mipmap.ic_launcher) // can also be a drawable .into(imageViewPlaceholder);
4) 當(dāng)加載圖片失敗時(shí),通過error(Drawable drawable)方法設(shè)置加載失敗后的圖片顯示:
Glide
.with(context)
.load("http://futurestud.io/non_existing_image.png")
.error(R.mipmap.future_studio_launcher) // will be displayed if the image cannot be loaded
.into(imageViewError);
5) 圖片的縮放,centerCrop()和fitCenter():
//使用centerCrop是利用圖片圖填充ImageView設(shè)置的大小,如果ImageView的 //Height是match_parent則圖片就會(huì)被拉伸填充 Glide.with(MainActivity.this) .load(args[position]) .centerCrop() .into(holder.imageView); //使用fitCenter即縮放圖像讓圖像都測(cè)量出來等于或小于 ImageView 的邊界范圍 //該圖像將會(huì)完全顯示,但可能不會(huì)填滿整個(gè) ImageView。 Glide.with(MainActivity.this) .load(args[position]) .fitCenter() .into(holder.imageView);
6) 顯示gif動(dòng)畫:
Glide .with( context ) .load( gifUrl ) .asGif() //判斷加載的url資源是否為gif格式的資源 .error( R.drawable.full_cake ) .into( imageViewGif );
7) 顯示本地視頻
String filePath = "/storage/emulated/0/Pictures/example_video.mp4"; Glide .with( context ) .load( Uri.fromFile( new File( filePath ) ) ) .into( imageViewGifAsBitmap );
8) 緩存策略:
Glide .with( context ) .load( Images[0] ) .skipMemoryCache( true ) //跳過內(nèi)存緩存 .into( imageViewInternet ); Glide .with( context ) .load( images[0] ) .diskCacheStrategy( DiskCacheStrategy.NONE ) //跳過硬盤緩存 .into( imageViewInternet );
- DiskCacheStrategy.NONE 什么都不緩存
- DiskCacheStrategy.SOURCE 僅僅只緩存原來的全分辨率的圖像
- DiskCacheStrategy.RESULT 僅僅緩存最終的圖像,即降低分辨率后的(或者是轉(zhuǎn)換后的)
- DiskCacheStrategy.ALL 緩存所有版本的圖像(默認(rèn)行為)
9) 優(yōu)先級(jí),設(shè)置圖片加載的順序:
Priority.LOW
Priority.NORMAL
Priority.HIGH
Priority.IMMEDIATE
private void loadImageWithHighPriority() {
Glide
.with( context )
.load( mages[0] )
.priority( Priority.HIGH )
.into( imageViewHero );
}
private void loadImagesWithLowPriority() {
Glide
.with( context )
.load( images[1] )
.priority( Priority.LOW )
.into( imageViewLowPrioLeft );
Glide
.with( context )
.load( images[2] )
.priority( Priority.LOW )
.into( imageViewLowPrioRight );
}
10) 當(dāng)不需要將加載的資源直接放入到ImageView中而是想獲取資源的Bitmap對(duì)象:
//括號(hào)中的300,600代表寬和高但是未有作用
SimpleTarget target = new SimpleTarget<Bitmap>(300,600) {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
holder.imageView.setImageBitmap(resource);
}
};
Glide.with(MainActivity.this)
.load(args[position])
.asBitmap()
.into(target);
11) 集成網(wǎng)絡(luò)棧(okHttp,Volley):
dependencies {
// your other dependencies
// ...
// Glide
compile 'com.github.bumptech.glide:glide:3.6.1'
// Glide's OkHttp Integration
compile 'com.github.bumptech.glide:okhttp-integration:1.3.1@aar'
compile 'com.squareup.okhttp:okhttp:2.5.0'
}
dependencies {
// your other dependencies
// ...
// Glide
compile 'com.github.bumptech.glide:glide:3.6.1'
// Glide's Volley Integration
compile 'com.github.bumptech.glide:volley-integration:1.3.1@aar'
compile 'com.mcxiaoke.volley:library:1.0.8'
}
好了,以上就是Glide動(dòng)態(tài)加載圖片的方法,下面開始本文的正文:
需求
Glide下載圖片并切圓角或圓形,但圖片有大有小,圖片不能改變,切圓還好說,但是切圓角就會(huì)發(fā)現(xiàn)圖片小的會(huì)比圖片大的要圓
搜一下 " Glide動(dòng)態(tài)加載圓形圖片跟圓角圖片 " 就會(huì)出現(xiàn)很多文章,但這些都不能解決上面的問題 怎樣能 Glide動(dòng)態(tài)加載不同大小的圖片切圓形圖片跟圓角圖片呢?
解決很簡(jiǎn)單
既然是圖片大小不一致而導(dǎo)致圖片切出來不一樣,那就把圖片變的一樣大小不就可以嗎
申明一下我的代碼也是在Glide動(dòng)態(tài)加載圓形圖片跟圓角圖片搜出來的代碼基礎(chǔ)上修改的. 下面就是代碼了.
build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
buildToolsVersion "26.0.2"
defaultConfig {
applicationId "cn.xm.weidongjian.glidedemo"
minSdkVersion 15
targetSdkVersion 26
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:26.1.0'
compile 'com.github.bumptech.glide:glide:3.6.1'
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="正常圖片" android:id="@+id/button" android:layout_alignParentTop="true" android:layout_centerHorizontal="true"/> <ImageView android:layout_width="72dp" android:layout_height="72dp" android:id="@+id/imageView" android:scaleType="fitCenter" android:layout_below="@+id/button" android:layout_alignRight="@+id/button" android:layout_alignEnd="@+id/button" android:layout_marginTop="150dp"/> <ImageView android:layout_width="72dp" android:layout_height="72dp" android:id="@+id/imageView2" android:scaleType="fitCenter" android:layout_below="@+id/imageView" android:layout_alignRight="@+id/imageView" android:layout_alignEnd="@+id/imageView" android:layout_marginTop="5dp" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="圓角圖片" android:id="@+id/button2" android:layout_below="@+id/button" android:layout_alignLeft="@+id/button" android:layout_alignRight="@+id/imageView" android:layout_alignEnd="@+id/imageView"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="大圓角圖片" android:id="@+id/button3" android:layout_below="@+id/button2" android:layout_alignLeft="@+id/button2" android:layout_alignStart="@+id/button2"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="圓形圖片" android:id="@+id/button4" android:layout_below="@+id/button3" android:layout_alignLeft="@+id/button" android:layout_alignRight="@+id/button3" android:layout_alignEnd="@+id/button3"/> </RelativeLayout>
MainActivity
package cn.xm.weidongjian.glidedemo;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
public class MainActivity extends AppCompatActivity implements OnClickListener {
private ImageView imageView;
private RequestManager glideRequest;
private Context context = this;
private ImageView imageView2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
findViewById(R.id.button).setOnClickListener(this);
findViewById(R.id.button2).setOnClickListener(this);
findViewById(R.id.button3).setOnClickListener(this);
findViewById(R.id.button4).setOnClickListener(this);
imageView = (ImageView) findViewById(R.id.imageView);
imageView2 = (ImageView) findViewById(R.id.imageView2);
glideRequest = Glide.with(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
glideRequest.load("http://androidop.le890.com/hma/upload/2016/10/11/1704146358.png").into(imageView);
glideRequest.load("http://androidop.le890.com/hma/upload/2016/10/11/1716089900.png").into(imageView2);
break;
case R.id.button2:
glideRequest.load("http://androidop.le890.com/hma/upload/2016/10/11/1704146358.png").transform(new GlideRoundTransform(context)).into(imageView);
glideRequest.load("http://androidop.le890.com/hma/upload/2016/10/11/1716089900.png").transform(new GlideRoundTransform(context)).into(imageView2);
break;
case R.id.button3:
glideRequest.load("http://androidop.le890.com/hma/upload/2016/10/11/1704146358.png").transform(new GlideRoundTransform(context, 7)).into(imageView);
glideRequest.load("http://androidop.le890.com/hma/upload/2016/10/11/1716089900.png").transform(new GlideRoundTransform(context, 7)).into(imageView2);
break;
case R.id.button4:
glideRequest.load("http://androidop.le890.com/hma/upload/2016/10/11/1704146358.png").transform(new GlideCircleTransform(context)).into(imageView);
glideRequest.load("http://androidop.le890.com/hma/upload/2016/10/11/1716089900.png").transform(new GlideCircleTransform(context)).into(imageView2);
break;
}
}
}
GlideCircleTransform
package cn.xm.weidongjian.glidedemo;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
public class GlideCircleTransform extends BitmapTransformation {
public GlideCircleTransform(Context context) {
super(context);
}
@Override protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
return circleCrop(pool, toTransform);
}
private static Bitmap circleCrop(BitmapPool pool, Bitmap source) {
if (source == null) return null;
int size = Math.min(source.getWidth(), source.getHeight());
int x = (source.getWidth() - size) / 2;
int y = (source.getHeight() - size) / 2;
// TODO this could be acquired from the pool too
Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);
Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
if (result == null) {
result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(result);
Paint paint = new Paint();
paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
paint.setAntiAlias(true);
float r = size / 2f;
canvas.drawCircle(r, r, r, paint);
return result;
}
@Override public String getId() {
return getClass().getName();
}
}
GlideRoundTransform
package cn.xm.weidongjian.glidedemo;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.Log;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
public class GlideRoundTransform extends BitmapTransformation {
private static float radius = 0f;
public GlideRoundTransform(Context context) {
this(context, 4);
}
public GlideRoundTransform(Context context, int dp) {
super(context);
this.radius = Resources.getSystem().getDisplayMetrics().density * dp;
}
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
return roundCrop(pool, toTransform);
}
private static Bitmap roundCrop(BitmapPool pool, Bitmap source) {
if (source == null) return null;
Bitmap bitmap = changeBitmapSize(source);
Bitmap result = pool.get(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_4444);
if (result == null) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
result = Bitmap.createBitmap(width,height, Bitmap.Config.ARGB_4444);
}
Canvas canvas = new Canvas(result);
Paint paint = new Paint();
paint.setShader(new BitmapShader(bitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
paint.setAntiAlias(true);
RectF rectF = new RectF(0f, 0f, bitmap.getWidth(), bitmap.getHeight());
canvas.drawRoundRect(rectF, radius, radius, paint);
return result;
}
public static Bitmap changeBitmapSize(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
//設(shè)置想要的大小
int newWidth=72;
int newHeight=72;
//計(jì)算壓縮的比率
float scaleWidth=((float)newWidth)/width;
float scaleHeight=((float)newHeight)/height;
//獲取想要縮放的matrix
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth,scaleHeight);
//獲取新的bitmap
bitmap=Bitmap.createBitmap(bitmap,0,0,width,height,matrix,true);
bitmap.getWidth();
bitmap.getHeight();
Log.e("newWidth","newWidth"+bitmap.getWidth());
Log.e("newHeight","newHeight"+bitmap.getHeight());
return bitmap;
}
@Override public String getId() {
return getClass().getName() + Math.round(radius);
}
}
很簡(jiǎn)單吧,就是用changeBitmapSize方法把圖片壓縮到72*72的這樣圖片都一樣大了,在切就不會(huì)出現(xiàn)切出來的圖片效果不一樣了
最后代碼(dome)
github地址: https://github.com/liang9/Imagedome
本地下載地址:http://xiazai.jb51.net/201711/yuanma/Imagedome(jb51.net).rar
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
- Android實(shí)現(xiàn)圓形圖片或者圓角圖片
- Android開發(fā)使用Drawable繪制圓角與圓形圖案功能示例
- Android自定義Drawable實(shí)現(xiàn)圓形和圓角
- Android中Glide加載圓形圖片和圓角圖片實(shí)例代碼
- Android自定義控件之圓形、圓角ImageView
- Android實(shí)現(xiàn)圓角矩形和圓形ImageView的方式
- Android自定義view實(shí)現(xiàn)圓形、圓角和橢圓圖片(BitmapShader圖形渲染)
- Android自定義控件之圓形/圓角的實(shí)現(xiàn)代碼
- android 實(shí)現(xiàn)圓角圖片解決方案
- Android基于Fresco實(shí)現(xiàn)圓角和圓形圖片
相關(guān)文章
利用OPENCV為android開發(fā)畸變校正的JNI庫(kù)方法
今天小編就為大家分享一篇利用OPENCV為android開發(fā)畸變校正的JNI庫(kù)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-08-08
解析Android中實(shí)現(xiàn)滑動(dòng)翻頁(yè)之ViewFlipper的使用詳解
有一些場(chǎng)景,我們需要向用戶展示一系列的頁(yè)面。比如我們正在開發(fā)一個(gè)看漫畫的應(yīng)用,可能就需要向用戶展示一張一張的漫畫圖片,用戶使用手指滑動(dòng)屏幕,可以在前一幅漫畫和后一幅漫畫之間切換。這個(gè)時(shí)候ViewFlipper就是一個(gè)很好的選擇2013-05-05
Android?AccessibilityService?事件分發(fā)原理分析總結(jié)
這篇文章主要介紹了Android?AccessibilityService?事件分發(fā)原理分析總結(jié),AccessibilityService有很多用來接收外部調(diào)用事件變化的方法,這些方法封裝在內(nèi)部接口Callbacks中,文章圍繞AccessibilityService相關(guān)資料展開詳情,需要的朋友可以參考一下2022-06-06
android Watchdog 實(shí)現(xiàn)剖析
Android提供了Watchdog類,用來監(jiān)測(cè)Service是否處于正常工作中,是在SystemServer中啟動(dòng)的;本文將詳細(xì)介紹2012-11-11
Android中SparseArray性能優(yōu)化的使用方法
這篇文章主要為大家詳細(xì)介紹了Android中SparseArray性能優(yōu)化的使用方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-04-04
教你3分鐘了解Android 簡(jiǎn)易時(shí)間軸的實(shí)現(xiàn)方法
本篇文章主要介紹了教你3分鐘了解Android 簡(jiǎn)易時(shí)間軸的實(shí)現(xiàn)方法,具有一定的參考價(jià)值,有興趣的可以了解一下2017-07-07
Android生存指南之:開發(fā)中的注意事項(xiàng)
本篇文章是對(duì)在Android開發(fā)中的一些注意事項(xiàng),需要的朋友可以參考下2013-05-05

