自定义Veiw之路(三)

2018-06-18  本文已影响0人  宁静世界

下面我们自定义一个圆形的图片

分为以下五部入手

1,拿到图片(Bitmap)
2,设置图片形状及模式BitmapShader
3,设置图片形状的变换矩阵,等比例缩放
4,为画笔设置shader(着色器)
5,将其绘制在画板上

需要掌握的

//BitmapShader 图片形状
//TileMode
//CLAMP 拉伸
//REPEAT 重复
//MIRROR 镜像
  bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
//Matrix 缩放矩阵
// shader的变换矩阵,我们这里主要用于放大或者缩小
mMatrix.setScale(scale, scale);
 // 设置变换矩阵
bitmapShader.setLocalMatrix(mMatrix);
// 设置着色器
mBitmapPaint.setShader(bitmapShader);

以下是示例代码

public class DiyView04 extends ImageView {

    private BitmapShader bitmapShader = null;
    private Bitmap bitmap = null;
    private int mWidth;
    private Matrix mMatrix;
    private Paint mBitmapPaint;
    private int mRadius;

    public DiyView04(Context context) {
        this(context, null);
    }

    public DiyView04(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DiyView04(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mMatrix = new Matrix();
        mBitmapPaint = new Paint();
        mBitmapPaint.setAntiAlias(true);

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        Log.e("TAG", "onMeasure");
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        mWidth = Math.min(getMeasuredWidth(), getMeasuredHeight());
        mRadius = mWidth / 2;
        setMeasuredDimension(mWidth, mWidth);
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        bitmap = ((BitmapDrawable) getResources().getDrawable(R.mipmap.img_main_orphan)).getBitmap();
        //TileMode
//        CLAMP 拉伸
//        REPEAT 重复
//        MIRROR 镜像
        bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        int bSize = Math.min(bitmap.getWidth(), bitmap.getHeight());
        float scale = 1.0f;
        scale = mWidth * 1.0f / bSize;
        // shader的变换矩阵,我们这里主要用于放大或者缩小
        mMatrix.setScale(scale, scale);
        // 设置变换矩阵
        bitmapShader.setLocalMatrix(mMatrix);
        // 设置shader
        mBitmapPaint.setShader(bitmapShader);
        canvas.drawCircle(mRadius, mRadius, mRadius, mBitmapPaint);
    }
}

上一篇 下一篇

猜你喜欢

热点阅读