码迷,mamicode.com
首页 > 移动开发 > 详细

Android自定义圆角ImageView

时间:2015-03-31 12:55:49      阅读:153      评论:0      收藏:0      [点我收藏+]

标签: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放到布局文件中使用就可以-----------------------------------

Android自定义圆角ImageView

标签:android应用   图片   imageview   

原文地址:http://blog.csdn.net/true100/article/details/44775583

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!