Android 使用圆角绘制ImageView时的效率
我有一个Android 使用圆角绘制ImageView时的效率,android,graphics,android-custom-view,Android,Graphics,Android Custom View,我有一个ImageView子类,用于绘制圆角图像。代码基于,如下所示: public class ImageViewRoundedCorners extends ImageView { ... @Override protected void onDraw(Canvas canvas) { Bitmap scaledBitmap = Bitmap.createBitmap(getMeasuredWidth(),
ImageView
子类,用于绘制圆角图像。代码基于,如下所示:
public class ImageViewRoundedCorners extends ImageView {
...
@Override
protected void onDraw(Canvas canvas) {
Bitmap scaledBitmap = Bitmap.createBitmap(getMeasuredWidth(),
getMeasuredHeight(),
Bitmap.Config.ARGB_8888);
Canvas scaledCanvas = new Canvas(scaledBitmap);
super.onDraw(scaledCanvas);
drawRoundedCornerBitmap(canvas, scaledBitmap,
getMeasuredWidth(), getMeasuredHeight());
scaledBitmap.recycle();
}
protected void drawRoundedCornerBitmap(Canvas outputCanvas, Bitmap input, int w, int h) {
Bitmap output = Bitmap.createBitmap(w, h, Config.ARGB_8888);
Canvas canvas = new Canvas(output);
mPaint.reset();
mPaint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
mPaint.setStyle(Paint.Style.FILL);
canvas.drawPath(mClipPath, mPaint);
mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(input, 0, 0, mPaint);
outputCanvas.drawBitmap(output, 0, 0, null);
}
}
使用此代码,图像将以适当的圆角绘制。为了避免在drawRoundedCornerBitmap
的前两行上进行分配,我想直接绘制到outputCanvas
,这是最初传递给onDraw
的画布。新的实现如下所示:
protected void drawRoundedCornerBitmap(...) {
mPaint.reset();
mPaint.setAntiAlias(true);
outputCanvas.drawARGB(0, 0, 0, 0);
mPaint.setStyle(Paint.Style.FILL);
outputCanvas.drawPath(mClipPath, mPaint);
mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
outputCanvas.drawBitmap(input, 0, 0, mPaint);
}
出于某种原因,此代码似乎忽略了Porter-Duff模式,而只是使用正常(非圆角)角绘制图像。为什么会这样?如何将原始代码绘制成中间的
位图
。我们不是链接工厂,但他的博客文章对此进行了广泛的解释,并提供了一种有效的方法
真正的基本原理是创建一个位图着色器
,并将其附加到一个绘制
对象,该对象绘制一个自定义的可绘制
,这样您只需将该可绘制
应用到图像视图
使用可绘制工具意味着图像只在画布上绘制一次,这意味着图像只绘制一次,然后ImageView所做的只是缩放可绘制工具。您是否找到了解决方案。。。甚至我也在尝试同样的事情:(当您必须在imageView中缩放该绘图时,这不是一种痛苦吗?绘图是创建的,然后拉伸或裁剪,这意味着您的角看起来会很奇怪,不是吗?记住
imageView
将您传递给它的任何内容转换为drawable
,提供其大小,然后调用draw()
在Drawable
上。默认情况下,如果您有一个BitmapDrawable,它当然只会拉伸它,当您传递一个RoundedBitmapDrawable
本身时,它将基于该实现进行绘制。