前言
Android 开发中,我们经常需要实现图片的圆形/圆角的效果,我们可以使用两种方式来实现这样的效果。一种是使用Xfermode,另一种是BitmapShader来实现。下面我将分别介绍这两种用法。
使用Xfermode的方式实现
使用该方式的关键代码,如下:
private Bitmap creataBitmap(Bitmap bitmap) {
//用指定的一个Bitmap来构建一个画布
Bitmap target = Bitmap.createBitmap(1000,1000, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(target);
final Paint paint = new Paint();
paint.setColor(Color.GREEN);
paint.setAntiAlias(true);
//在刚才的画布上绘制一个圆形区域
canvas.drawCircle(500,500,500,paint);
//设置Xfermode,使用SRC_IN模式,这样可以取到第二张图片重叠后的区域
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
//在画布上绘制第二个需要显示的bitmap
canvas.drawBitmap(bitmap,0,0,paint);
return target;
}
上面代码中看出在指定的画布上绘制了两层图像,一个是半径为500像素的圆形,一个是将目标Bitmap绘制在上面。之间还调用了paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));作用是这两个绘制的效果图叠加后,取得第二个图的交集图。所以,我们先绘制一个圆形,然后绘制Bitmap,交集为圆形,取出的就是圆形区域的Bitmap了。
PorterDuff.Mode中一共有16种效果显示,如下:
可以根据不同的Mode,控制显示的效果图。
开始应用
1.自定义属性在attrs.xml中
2.自定义View
public class RoundImageView extends View {
private int type;
private static final int TYPE_CIRCLE = 0;
private static final int TYPE_ROUND = 1;
//图片
private Bitmap mSrc;
//圆角大小
private int mRadius;
//高度
private int mWidth;
//宽度
private int mHeight;
public RoundImageView(Context context, AttributeSet attrs) {
super(context, attrs);
//获取自定义的属性
TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.RoundImageView);
//获取自定以属性的数目
int count = a.getIndexCount();
for (int i=0 ; i
3.布局文件
上面的自定义View中,存在一个局限,那就是只能在布局中设置要加载的图片资源,不能在代码中设置图片。下面我们使用同样的方式,选择自定义ImageView来实现。
public class RoundImageView extends ImageView {
private int type;
private static final int TYPE_CIRCLE = 0;
private static final int TYPE_ROUND = 1;
//图片
private Bitmap mSrc;
//圆角大小
private int mRadius;
public RoundImageView(Context context, AttributeSet attrs) {
super(context, attrs);
//获取自定义的属性
TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.RoundImageView);
//获取自定以属性的数目
int count = a.getIndexCount();
for (int i=0 ; i
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



