我应该如何在 Android 中给图像圆角? [英] How should I give images rounded corners in Android?

查看:24
本文介绍了我应该如何在 Android 中给图像圆角?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将我加载的图像更改为具有圆角.

I would like to change an image I loaded to have round corners.

您知道任何提示、教程和最佳做法吗?

Any hints, tutorials, best practices you know of?

推荐答案

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

For a more controlled method draw a rounded rectangle and mask it onto your image using the porter-duff Xfer mode of the paint.

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

First setup the Xfer paint and the rounded bitmap:

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));

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

Now apply this bitmap ontop of your image:

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);

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

Bitmap with rounded corners now resides in result.

这篇关于我应该如何在 Android 中给图像圆角?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆