欢迎来到代码驿站!

Android代码

当前位置:首页 > 移动开发 > Android代码

Android将Glide动态加载不同大小的图片切圆角与圆形的方法

时间:2020-11-07 22:01:15|栏目:Android代码|点击:

Glide加载动态图片

首先我们先要去依赖一个githup:bumptech: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.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)    当不需要将加载的资源直接放入到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

本地下载地址:http://xiazai.jb51.net/201711/yuanma/Imagedome(jb51.net).rar

总结

上一篇:Android带进度的圆形进度条

栏    目:Android代码

下一篇:Android自定义EditText实现登录界面

本文标题:Android将Glide动态加载不同大小的图片切圆角与圆形的方法

本文地址:http://www.codeinn.net/misctech/20130.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有