欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2022-06-29 08:28:53
glide加载动态图片 首先我们先要去依赖一个githup:bumptech:glide:glide:3.7.0包; 使用glide结合列表的样式进行图片加载:...

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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。