java - 我应该如何在 Android 中给图像圆角?

标签 java android image

我想将加载的图像更改为圆角。

您知道的任何提示、教程、最佳实践吗?

最佳答案

对于一个更可控的方法,绘制一个圆角矩形,并使用绘画的 porter-duff Xfer 模式将其蒙版到您的图像上。

首先设置 Xfer 绘制和圆角位图:

Bitmap myCoolBitmap = ... ; // <-- Your bitmap you want rounded    
int w = myCoolBitmap.getWidth(), h = myCoolBitmap.getHeight();

// We have to make sure our rounded corners have an alpha channel in most cases
Bitmap rounder = Bitmap.createBitmap(w,h,Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(rounder);    

// We're going to apply this paint eventually using a porter-duff xfer mode.
// This will allow us to only overwrite certain pixels. RED is arbitrary. This
// could be any color that was fully opaque (alpha = 255)
Paint xferPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
xferPaint.setColor(Color.RED);

// We're just reusing xferPaint to paint a normal looking rounded box, the 20.f
// is the amount we're rounding by.
canvas.drawRoundRect(new RectF(0,0,w,h), 20.0f, 20.0f, xferPaint);     

// Now we apply the 'magic sauce' to the paint  
xferPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));

现在将此位图应用到您的图像上:

Bitmap result = Bitmap.createBitmap(myCoolBitmap.getWidth(), myCoolBitmap.getHeight() ,Bitmap.Config.ARGB_8888);
Canvas resultCanvas = new Canvas(result)
resultCanvas.drawBitmap(myCoolBitmap, 0, 0, null);
resultCanvas.drawBitmap(rounder, 0, 0, xferPaint);

圆角位图现在驻留在结果中。

关于java - 我应该如何在 Android 中给图像圆角?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1705239/

相关文章:

javascript - 不要载入隐藏图片

php - 我们如何使用 PHP 代码删除图像白色背景颜色

java - 如何从 Java 引发 Jython 异常?

java - LibGDX - 设置背景图像(静态)

android - 无法加载 Nexus 7 USB 驱动程序以在 WinXP 上进行 Android 调试

java - 从关系数据库检索数据

java - 检查集合是否包含对象,按引用进行比较

java - 如何修复 BoneCP 中的 : Exception in thread "main" java. lang.NoClassDefFoundError

java - Android 使用 MediaRecorder 采集音频。

javascript - 使用 Javascript 中的 Select 值预览图像