兩種方式實現圖形圖片

本文介紹兩種實現圖形圖片的方法。
1.通過裁剪bitmap, 使用PorterDuffXfermode, 可以參考這篇博客
http://blog.csdn.net/edisonlg/article/details/7084977
2.通過設置渲染器 BitmapShader, 使用一張圖片創建一支具有圖像填充功能的畫筆

具體代碼如下

public class CircleImageView extends ImageView {
    private Bitmap srcBitmap;
    private Rect rect;
    private Paint paint;
    private BitmapShader mBitmapShader;
    private int mRadius;
    private Matrix mMatrix;

    public CircleImageView(Context context) {
        super(context);
        init();
    }


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

    public CircleImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }


    /**
     * 初始化變量
     */
    private void init() {
        paint = new Paint();
        paint.setAntiAlias(true);
        srcBitmap = ((BitmapDrawable) getDrawable()).getBitmap();
        mMatrix = new Matrix();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

        if (getWidth() > 0 && getHeight() > 0) {
            rect = new Rect(0, 0, getWidth(), getHeight());
            int mWidth = Math.min(getMeasuredWidth(), getMeasuredHeight());
            mRadius = mWidth / 2;

            //計算縮放比例
      int bSize = Math.min(srcBitmap.getWidth(), srcBitmap.getHeight());
            float scale = mWidth * 1.0f / bSize;
            mMatrix.setScale(scale, scale);

        }
    }

    @Override
    protected void onDraw(Canvas canvas) {


        // 方式1.通過裁剪bitmap
      //  canvas.drawBitmap(createCricleBitmap(srcBitmap), rect, rect, null);


        //方式2.通過設置渲染器
        mBitmapShader = new BitmapShader(srcBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);

    // 設置縮放
     mBitmapShader.setLocalMatrix(mMatrix);
        paint.setShader(mBitmapShader);
        canvas.drawCircle(mRadius,
                mRadius,
                mRadius,
                paint);


    }

    /**
     * 獲取裁剪後的圓形圖片
     *
     * @param bitmap
     * @return
     */
    private Bitmap createCricleBitmap(Bitmap bitmap) {
        Bitmap outBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(),
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(outBitmap);
        canvas.drawCircle(mRadius,
                mRadius,
                mRadius,
                paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, mMatrix, paint);
        return outBitmap;

    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章