1. 程式人生 > >超簡潔代碼實現CircleImageView

超簡潔代碼實現CircleImageView

技術分享 length cti nds .config reset 緩存 類型 lines

效果圖:

技術分享

頁面代碼:

public class CircleView extends ImageView {
    private Paint mPaint = new Paint();

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


    @Override
    protected void onDraw(Canvas canvas) {
        Drawable mDrawable = getDrawable();//獲取xml文件設置的圖片
if (null == mDrawable) super.onDraw(canvas);//假設為空,交給父類處理 Bitmap mBitmap = ((BitmapDrawable) mDrawable).getBitmap();//將圖片轉化成bitmap int len = getWidth() < getHeight() ?

getWidth() : getHeight();//獲取xml的長寬屬性值,選擇較小的 Bitmap tempBitmap = Bitmap.createBitmap(len, len, Bitmap.Config.ARGB_8888);//新建一個bitmap對象。作為緩存

Canvas mCanvas = new Canvas(tempBitmap);//新建畫布緩存bitmap對象 mPaint.setAntiAlias(true);//抗鋸齒 mCanvas.drawCircle(len / 2, len / 2, len / 2, mPaint);//畫一個圓 mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));//設置畫筆的覆蓋類型 Matrix matrix = new Matrix(); // 初始化Matrix對象
matrix.setScale((float) len / mBitmap.getWidth(), (float) len / mBitmap.getHeight()); //設置縮放比例 mCanvas.drawBitmap(mBitmap, matrix, mPaint);//畫出縮放後的圖片 mPaint.reset();//重置畫筆 canvas.drawBitmap(tempBitmap, 0, 0, mPaint);//繪制緩存圖片 } }

超簡潔代碼實現CircleImageView