首页 > 学院 > 开发设计 > 正文

Glide 加载圆角或圆形图片

2019-11-07 22:59:05
字体:
来源:转载
供稿:网友

Glide的基础使用网上有很多,请自行查阅。

圆角和圆形图片如果是本地或者已知的Bitmap,建议大家使用Android supportV4 包中的RoundedBitmapDrawable.

先上效果图

这里写图片描述这里写图片描述 具体思路如下 1、使用Glide的transform方法 2、继承BitmapTransformation实现以便传入transform参数 3、实现BitmapTransformation的一个抽象方法transform 4、通过BitmapShader绘制图片样式

圆形图片

public class GlideCircleTransform extends BitmapTransformation { PRivate int radius = 20; public GlideCircleTransform(Context context) { super(context); } public GlideCircleTransform(BitmapPool bitmapPool) { super(bitmapPool); } @Override protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) { return roundCrop(pool, toTransform, outWidth, outHeight); } private Bitmap roundCrop(BitmapPool pool, Bitmap source, int outWidth, int outHeight) { 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; 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, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)); paint.setAntiAlias(true); int radius = size / 2; canvas.drawCircle(radius, radius, radius, paint); return result; } @Override public String getId() { return getClass().getName(); }}

注意: 这里既然是我们自己做的绘制,就会有个问题就是ImageViewandroid:scaleType 属性可能会失效,尤其是android:scaleType="centerCrop"已经失效,因为我们是固定截取的一张图片正中心的位置,所以如果是正方形的图片自然不存在该问题。

圆角图片

private Bitmap roundCrop(BitmapPool pool, Bitmap source) { if (source == null) return null; int width = source.getWidth(); int height = source.getHeight(); Bitmap result = pool.get(width, height, Bitmap.Config.ARGB_8888); if (result == null) { result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); } Canvas canvas = new Canvas(result); Paint paint = new Paint(); paint.setShader(new BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)); paint.setAntiAlias(true); RectF rectF = new RectF(0f, 0f, width, height); canvas.drawRoundRect(rectF, radius, radius, paint); return result; }
上一篇:静态库

下一篇:Win10开发笔记11

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表