前言
創(chuàng)新互聯(lián)專注于孝義企業(yè)網(wǎng)站建設(shè),成都響應(yīng)式網(wǎng)站建設(shè),商城網(wǎng)站定制開發(fā)。孝義網(wǎng)站建設(shè)公司,為孝義等地區(qū)提供建站服務(wù)。全流程定制網(wǎng)站設(shè)計,專業(yè)設(shè)計,全程項目跟蹤,創(chuàng)新互聯(lián)專業(yè)和態(tài)度為您提供的服務(wù)相信大家在Android日常開發(fā)中,繪制圓形和繪制圖片都是很容易的事情,但是繪制圓形圖片就有點難倒人了。以前為了偷懶就直接去github上找一個開源項目,后來才發(fā)現(xiàn)繪制圓形圖片其實也是很簡單的事。
繪制圓形圖片也需要兩個步驟:
繪制圓形和繪制圖片,只不過要讓它們?nèi)〔⒓?,得到的結(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); } }