Android 使用Universal Image Loader绘制带圆角的图片(一)
- 绘制带圆角的控件难吗?貌似不难。对于一个普通layout或者widget,要绘制圆角,只要把 background设置成下面这样的drawable就行了。
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <!-- 填充的颜色 --> <solid android:color="@color/pure_white" /> <!-- 设置按钮的四个角为弧形 --> <!-- android:radius 弧形的半径 --> <corners android:radius="@dimen/small_corner_radius" /> </shape>
但是,对于图片控件ImageView,这种方法却会没有效果。要想知道原因,就得看android源码。首先看看ImageView是如何设置Bitmap的。
public void setImageBitmap(Bitmap bm) { // if this is used frequently, may handle bitmaps explicitly // to reduce the intermediate drawable object setImageDrawable(new BitmapDrawable(mContext.getResources(), bm)); }
哦,它通过Bitmap创建了一个BitmapDrawable。那BitmapDrawable干了啥呢?
@Override public void draw(Canvas canvas) { Bitmap bitmap = mBitmap; if (bitmap != null) { final BitmapState state = mBitmapState; if (state.mRebuildShader) { ...... if (tmx == null && tmy == null) { state.mPaint.setShader(null); } else { state.mPaint.setShader(new BitmapShader(bitmap, tmx == null ? Shader.TileMode.CLAMP : tmx, tmy == null ? Shader.TileMode.CLAMP : tmy)); } ....... copyBounds(mDstRect); } Shader shader = state.mPaint.getShader(); final boolean needMirroring = needMirroring(); if (shader == null) { ...... canvas.drawBitmap(bitmap, null, mDstRect, state.mPaint); if (needMirroring) { canvas.restore(); } } else { ...... canvas.drawRect(mDstRect, state.mPaint); } } }
注意红色的代码,可以大概知道,这里仅仅把图片绘制到了一个固定的矩形框中,所以图片部分还是矩形。
那么该如何解决这个问题呢?还好并不复杂,看看十分流行的UIL(Universal Image Loader https://github.com/nostra13/Android-Universal-Image-Loader )是怎么做的。答案就在它的RoundedBitmapDisplayer.java中的RoundedDrawable类。
public static class RoundedDrawable extends Drawable { public RoundedDrawable(Bitmap bitmap, int cornerRadius, int margin, ViewScaleType scaleType) { this.cornerRadius = cornerRadius; this.margin = margin; bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); mBitmapRect = new RectF (margin, margin, bitmap.getWidth() - margin, bitmap.getHeight() - margin); paint = new Paint(); paint.setAntiAlias(true); paint.setShader(bitmapShader); mScaleType = scaleType; } @Override public void draw(Canvas canvas) { canvas.drawRoundRect(mRect, cornerRadius, cornerRadius, paint); //canvas.drawRect(mDstRect, state.mPaint); ImageView的绘制方法?} }
我只贴出了构造器和draw两个方法。构造器的代码表明它也是用BitmapShader来进行图片的绘制的,和ImageView的区别就在于,它是用drawRoundRect的方法来进行绘制的。所以它可以绘制出圆角的图片。
Edit By MaHua
时间: 2024-10-19 11:10:57