国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Android > 正文

Android將Glide動態加載不同大小的圖片切圓角與圓形的方法

2019-10-22 18:23:05
字體:
來源:轉載
供稿:網友

Glide加載動態圖片

首先我們先要去依賴一個githup:bumptech:android/252444.html">glide:glide:3.7.0包;

使用Glide結合列表的樣式進行圖片加載:

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)    當加載網絡圖片時,由于加載過程中圖片未能及時顯示,此時可能需要設置等待時的圖片,通過placeHolder()方法:

Glide .with(context) .load(UsageExampleListViewAdapter.eatFoodyImages[0]) .placeholder(R.mipmap.ic_launcher) // can also be a drawable .into(imageViewPlaceholder);

4) 當加載圖片失敗時,通過error(Drawable drawable)方法設置加載失敗后的圖片顯示:

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設置的大小,如果ImageView的//Height是match_parent則圖片就會被拉伸填充Glide.with(MainActivity.this)   .load(args[position])   .centerCrop()   .into(holder.imageView);//使用fitCenter即縮放圖像讓圖像都測量出來等于或小于 ImageView 的邊界范圍//該圖像將會完全顯示,但可能不會填滿整個 ImageView。Glide.with(MainActivity.this)   .load(args[position])   .fitCenter()   .into(holder.imageView);

6)    顯示gif動畫:

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 ) //跳過內存緩存 .into( imageViewInternet );Glide  .with( context ) .load( images[0] ) .diskCacheStrategy( DiskCacheStrategy.NONE ) //跳過硬盤緩存 .into( imageViewInternet );
  • DiskCacheStrategy.NONE 什么都不緩存
  • DiskCacheStrategy.SOURCE 僅僅只緩存原來的全分辨率的圖像
  • DiskCacheStrategy.RESULT 僅僅緩存最終的圖像,即降低分辨率后的(或者是轉換后的)
  • DiskCacheStrategy.ALL 緩存所有版本的圖像(默認行為)

9)    優先級,設置圖片加載的順序:

Priority.LOWPriority.NORMALPriority.HIGHPriority.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)    當不需要將加載的資源直接放入到ImageView中而是想獲取資源的Bitmap對象:

//括號中的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)    集成網絡棧(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動態加載圖片的方法,下面開始本文的正文:

需求

Glide下載圖片并切圓角或圓形,但圖片有大有小,圖片不能改變,切圓還好說,但是切圓角就會發現圖片小的會比圖片大的要圓
搜一下 " Glide動態加載圓形圖片跟圓角圖片 " 就會出現很多文章,但這些都不能解決上面的問題 怎樣能 Glide動態加載不同大小的圖片切圓形圖片跟圓角圖片呢?

解決很簡單

既然是圖片大小不一致而導致圖片切出來不一樣,那就把圖片變的一樣大小不就可以嗎

申明一下我的代碼也是在Glide動態加載圓形圖片跟圓角圖片搜出來的代碼基礎上修改的. 下面就是代碼了.

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(); //設置想要的大小 int newWidth=72; int newHeight=72; //計算壓縮的比率 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); }}

很簡單吧,就是用changeBitmapSize方法把圖片壓縮到72*72的這樣圖片都一樣大了,在切就不會出現切出來的圖片效果不一樣了

最后代碼(dome)

github地址: https://github.com/liang9/Imagedome

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對VEVB武林網的支持。


注:相關教程知識閱讀請移步到Android開發頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 东海县| 高陵县| 河西区| 滦平县| 灵石县| 鹤山市| 菏泽市| 栖霞市| 六安市| 贡嘎县| 永新县| 鹤庆县| 嘉义县| 浮梁县| 封丘县| 绥阳县| 蓬溪县| 三原县| 鄱阳县| 运城市| 溆浦县| 山西省| 华宁县| 安化县| 丽水市| 伊宁县| 台州市| 永泰县| 夏津县| 富宁县| 兴义市| 盐亭县| 枣庄市| 汶上县| 凤山县| 信宜市| 尼勒克县| 壶关县| 莆田市| 通许县| 铅山县|