您好,登錄后才能下訂單哦!
這篇文章主要介紹了Android如何將Glide動(dòng)態(tài)加載不同大小的圖片切圓角與圓形,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
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í),由于加載過(guò)程中圖片未能及時(shí)顯示,此時(shí)可能需要設(shè)置等待時(shí)的圖片,通過(guò)placeHolder()方法:
Glide .with(context) .load(UsageExampleListViewAdapter.eatFoodyImages[0]) .placeholder(R.mipmap.ic_launcher) // can also be a drawable .into(imageViewPlaceholder);
4) 當(dāng)加載圖片失敗時(shí),通過(guò)error(Drawable drawable)方法設(shè)置加載失敗后的圖片顯示:
Glide .with(context) .load("https://cache.yisu.com/upload/information/20200623/125/125610.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è)量出來(lái)等于或小于 ImageView 的邊界范圍 //該圖像將會(huì)完全顯示,但可能不會(huì)填滿整個(gè) ImageView。 Glide.with(MainActivity.this) .load(args[position]) .fitCenter() .into(holder.imageView);
6) 顯示gif動(dòng)畫(huà):
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 ) //跳過(guò)內(nèi)存緩存 .into( imageViewInternet ); Glide .with( context ) .load( images[0] ) .diskCacheStrategy( DiskCacheStrategy.NONE ) //跳過(guò)硬盤緩存 .into( imageViewInternet );
DiskCacheStrategy.NONE 什么都不緩存
DiskCacheStrategy.SOURCE 僅僅只緩存原來(lái)的全分辨率的圖像
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)加載圖片的方法,下面開(kāi)始本文的正文:
需求
Glide下載圖片并切圓角或圓形,但圖片有大有小,圖片不能改變,切圓還好說(shuō),但是切圓角就會(huì)發(fā)現(xiàn)圖片小的會(huì)比圖片大的要圓
搜一下 " Glide動(dòng)態(tài)加載圓形圖片跟圓角圖片 " 就會(huì)出現(xiàn)很多文章,但這些都不能解決上面的問(wèn)題 怎樣能 Glide動(dòng)態(tài)加載不同大小的圖片切圓形圖片跟圓角圖片呢?
解決很簡(jiǎn)單
既然是圖片大小不一致而導(dǎo)致圖片切出來(lái)不一樣,那就把圖片變的一樣大小不就可以嗎
申明一下我的代碼也是在Glide動(dòng)態(tài)加載圓形圖片跟圓角圖片搜出來(lá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)切出來(lái)的圖片效果不一樣了
感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“Android如何將Glide動(dòng)態(tài)加載不同大小的圖片切圓角與圓形”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來(lái)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。