Android自定义圆角ImageView


public class MyCirleImageView extends ImageView {


private static int RADIUS = 4; // 默认圆角的宽高是8dip,可以设置有参构造,传入需要的值

public MyCirleImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}

@Override
protected void onDraw(Canvas canvas) {
/**取得Drawable*/
BitmapDrawable drawable = (BitmapDrawable) getDrawable();
if (drawable == null) { return; }
if (getWidth() == 0 || getHeight() == 0) { return; }
/**取得对应bitmap*/
Bitmap fullBitmap = drawable.getBitmap();
/**取得View在parent view里面占的大小
* getWidth得到的事某个View的实际尺寸。getMeasuredWidth是某个View想要在parent view里面占的大小
*/
int scaledWidth = getMeasuredWidth();
int scaledHeight = getMeasuredHeight();

Bitmap mScaledBitmap;
if (scaledWidth == fullBitmap.getWidth() && scaledHeight == fullBitmap.getHeight()) {
mScaledBitmap = fullBitmap;
} else {
mScaledBitmap = Bitmap.createScaledBitmap(fullBitmap, scaledWidth, scaledHeight, true);
}

try {
Bitmap roundBitmap = getRoundedCornerBitmap(getContext(), mScaledBitmap, RADIUS, scaledWidth, scaledHeight, false, false, false, false);
canvas.drawBitmap(roundBitmap, 0, 0, null);
} catch (Exception e) {
super.onDraw(canvas);
}
}


/**取得圆角图片*/
public static Bitmap getRoundedCornerBitmap(Context context, Bitmap input, int pixels, int w, int h, boolean squareTL, boolean squareTR, boolean squareBL, boolean squareBR) {

Bitmap output = Bitmap.createBitmap(w, h, Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final float mulitDensity = context.getResources().getDisplayMetrics().density;

final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, w, h);
final RectF rectF = new RectF(rect);
final float roundPx = pixels * mulitDensity;

paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

/**下面几个判断是实现:是否要保留对应直角*/
if (squareTL) {
canvas.drawRect(0, 0, w / 2, h / 2, paint);
}
if (squareTR) {
canvas.drawRect(w / 2, 0, w, h / 2, paint);
}
if (squareBL) {
canvas.drawRect(0, h / 2, w / 2, h, paint);
}
if (squareBR) {
canvas.drawRect(w / 2, h / 2, w, h, paint);
}
/**设置两张图片相交时的模式。
* 在正常的情况下,在已有的图像上绘图将会在其上面添加一层新的形状。如果新的Paint是完全不透明的,那么它将完全遮挡住下面的Paint;如果它是部分透明的,那么它将会被染上下面的颜色。
* 而setXfermode就可以来解决这个问题 
* paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));    
* canvas.drawBitmap(srcBitmap, 0f, 0f, paint); canvas原有的图片可以理解为背景,就是dst;新画上去的图片可以理解为前景,就是src。
* */
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(input, 0, 0, paint);
return output;
}

}

-----------------------把MyCirleImageView 当成ImageView放到布局文件中使用就可以-----------------------------------

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。