gpt4 book ai didi

android - 绘制带圆角的ImageView时的效率

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:45:18 24 4
gpt4 key购买 nike

我有一个 ImageView 子类,我用它来绘制带有圆角的图像。代码基于this answer , 如下:

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 的 Canvas 。新的实现看起来像这样:

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 模式,而只是绘制具有正常(非圆角)角的图像。为什么会这样?绘制到使原始代码工作的中间 Bitmap 是什么意思?

最佳答案

创建可绘制对象 Romain Guy 已为您完成此操作。我们不是链接工厂,但他的博客文章对其进行了相当广泛的解释,并提供了一种有效的方法。 Rounded Corners

真正的基本原理,是创建一个 BitmapShader 并将其附加到一个 Paint 对象,该对象以您所需要的方式绘制自定义 Drawable将该 Drawable 应用于 ImageView

使用 drawable 意味着图像只被绘制到 Canvas 上一次,这意味着绘制图像只完成一次,然后 ImageView 所做的只是缩放 drawable。

关于android - 绘制带圆角的ImageView时的效率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11889531/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com