在Android中霞丧,繪制圓形和繪制圖片都是很容易的事情目锭,但是繪制圓形圖片就有點(diǎn)難倒人了厌秒。以前為了偷懶就直接去github上找一個(gè)開源項(xiàng)目,后來才發(fā)現(xiàn)繪制圓形圖片其實(shí)也是很簡單的事汉形。繪制圓形圖片也需要兩個(gè)步驟:繪制圓形和繪制圖片纸镊,只不過要讓它們?nèi)〔⒓玫降慕Y(jié)果就是一張圓形圖片了概疆。直接上代碼逗威。
public class CircleImageView extends View {
private Paint mPaint;
private Paint mTargetPaint;
private Bitmap mSourceBitmap;
private Bitmap mTargetBitmap;
private Canvas mTargetCanvas;
private int mWidth;
private int mHeight;
public CircleImageView(Context context) {
this(context, null);
}
public CircleImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CircleImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mTargetPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mTargetPaint.setXfermode(new PorterDuffXfermode(SRC_IN));
mSourceBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.xiaojiangshi);
mTargetBitmap = Bitmap.createBitmap(mSourceBitmap.getWidth(), mSourceBitmap.getHeight(), Bitmap.Config.ARGB_8888);
mTargetCanvas = new Canvas(mTargetBitmap);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mWidth = w;
mHeight = h;
}
@Override
protected void onDraw(Canvas canvas) {
// 生成圓形Bitmap過程.
int radius = Math.min(mWidth, mHeight) / 2;
// 先繪制圓形
mTargetCanvas.drawCircle(mWidth / 2, mHeight / 2, radius, mPaint);
// 再繪制Bitmap
mTargetCanvas.drawBitmap(mSourceBitmap, 0, 0, mTargetPaint);
canvas.drawBitmap(mTargetBitmap, 0, 0, null);
}
}
效果如下:
代碼中最關(guān)鍵的就是這句:
mTargetPaint.setXfermode(new PorterDuffXfermode(SRC_IN));
SRC_IN
這種模式可以讓兩個(gè)繪制的效果取交集后展現(xiàn)出來,需要注意的是届案,dst需要先繪制庵楷,再繪制src,拿上面例子來說楣颠,就是要先繪制圓形尽纽,在繪制Bitmap,如果順序顛倒了童漩,你就只能看到一個(gè)圓形了弄贿。
除了SRC_IN
這種模式外,還有其它15種模式矫膨。有興趣的可以自己試試看效果差凹。在官方提供的APIDemo中可以找到相應(yīng)的代碼。
知道這個(gè)原理之后侧馅,我們就能繪制各種形狀的圖片了危尿,只需要繪制不同的形狀代替繪制圓形這一步驟就可以了。
三角形:
mPath.reset();
mPath.moveTo(mWidth / 2, 0);
mPath.lineTo(0, mHeight);
mPath.lineTo(mWidth, mHeight);
mPath.close();
mTargetCanvas.drawPath(mPath, mPaint);
扇形:
RectF rectF = new RectF(0, 0, mWidth, mHeight);
mTargetCanvas.drawArc(rectF, 210, 120, true, mPaint);