package com.sclgxt.customimageview;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.widget.ImageView;
/**
* Created by Sclgxt on 2016/5/5.
* Mind:圆角图片,如果不是wrapcontent,
* 请注意加上这句话android:scaleType="centerCrop",防止图片撑不起来而留有空
* 请注意setRoundCorner.
*/
public class RoundCornerImageView extends ImageView {
private Paint roundPaint;
private Paint maskPaint;
private int size = 0;
public RoundCornerImageView(Context context) {
this(context, null);
}
public RoundCornerImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public RoundCornerImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
init();
}
private void init() {
roundPaint = new Paint();
roundPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER));
roundPaint.setAntiAlias(true);
roundPaint.setColor(Color.WHITE);
maskPaint = new Paint();
maskPaint.setAntiAlias(true);
maskPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
}
@Override
protected void onDraw(Canvas canvas) {
canvas.saveLayer(0, 0, getWidth(), getHeight(),
roundPaint, Canvas.ALL_SAVE_FLAG);
canvas.drawRoundRect(new RectF(0, 0, getWidth(), getHeight()), size, size, roundPaint);
canvas.saveLayer(0, 0, getWidth(), getHeight(), maskPaint, Canvas.ALL_SAVE_FLAG);
super.onDraw(canvas);
}
//设置圆角大小.这是一种写法,当然也可以自定义属性咯
public void setRoundCorner(int size) {
this.size = size;
}
}