走向远方

是男儿总要走向远方,走向远方是为了让生命更辉煌

Android自定义View——可设置形状(圆形、圆角矩形、椭圆)的ImageView,抗锯齿
(如果对自定义View不太熟悉,可以查看上篇文章《Android自定义View——基础知识篇》)

有时显示的图片(如用户头像)是圆形或者圆角矩形的,如果我们把每一种形状的图片都裁剪成一个图片文件,这样既麻烦也浪费空间,所以最好的办法是通过代码来设置图片的显示形状。显示图片用到的是ImageView,最简单的设置图片形状的方法就是在draw()里面通过canvas.clipPath()把画布裁剪成相应形状,但这种方法有个很大的缺点,就是边缘锯齿明显。

这里我通过BitmapShader来绘制图片,可以很好地解决锯齿的问题,将画笔的渲染器设置成BitmapShader,则通过画笔绘制的图案则以图片为背景。关键步骤为:

// 获取图片
Bitmap bitmap = Util.getBitmapFromDrawable(getDrawable());
// 设置图片渲染器
mBitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
// 把渲染器放入画笔中
mBitmapPaint.setShader(mBitmapShader);
// 在画布上画圆,即可绘制出圆形图片
canvas.drawCircle(cx, cy, radius, mBitmapPaint);

效果如下:



关键代码:
public class ShapeImageView extends ImageView {

    public static int SHAPE_REC = 1; // 矩形
    public static int SHAPE_CIRCLE = 2; // 圆形
    public static int SHAPE_OVAL = 3; // 椭圆

    private float mBorderSize = 0; // 边框大小,默认为0,即无边框
    private int mBorderColor = Color.WHITE; // 边框颜色,默认为白色
    private int mShape = SHAPE_REC; // 形状,默认为直接矩形
    private float mRoundRadius = 0; // 矩形的圆角半径,默认为0,即直角矩形
    private Paint mBorderPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private RectF mViewRect = new RectF(); // imageview的矩形区域
    private RectF mBorderRect = new RectF(); // 边框的矩形区域

    private final Matrix mShaderMatrix = new Matrix();
    private Paint mBitmapPaint = new Paint();
    private BitmapShader mBitmapShader;
    private Bitmap mBitmap;

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

    public ShapeImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle); // 虽然此处会调用setImageDrawable,但此时成员变量还未被正确初始化
        init(attrs);
        mBorderPaint.setStyle(Style.STROKE);
        mBorderPaint.setStrokeWidth(mBorderSize);
        mBorderPaint.setColor(mBorderColor);
        mBorderPaint.setAntiAlias(true);
        mBitmapPaint.setAntiAlias(true);
        super.setScaleType(ScaleType.CENTER_CROP); // 固定为CENTER_CROP,其他不生效
    }


    @Override
    public void setImageResource(int resId) {
        super.setImageResource(resId);
        mBitmap = Util.getBitmapFromDrawable(getDrawable());
        setupBitmapShader();
    }

    @Override
    public void setImageDrawable(Drawable drawable) {
        super.setImageDrawable(drawable);
        mBitmap = Util.getBitmapFromDrawable(drawable);
        setupBitmapShader();
    }

    @Override
    public void setScaleType(ScaleType scaleType) {
        if (scaleType != ScaleType.CENTER_CROP) {
            throw new IllegalArgumentException(String.format("ScaleType %s not supported.", scaleType));
        }
    }

    private void init(AttributeSet attrs) {

        TypedArray a = getContext().obtainStyledAttributes(attrs,
                R.styleable.ShapeImageView);
        mShape = a.getInt(R.styleable.ShapeImageView_shape, mShape);
        mRoundRadius = a.getDimension(R.styleable.ShapeImageView_round_radius, mRoundRadius);
        mBorderSize = a.getDimension(R.styleable.ShapeImageView_border_size, mBorderSize);
        mBorderColor = a.getColor(R.styleable.ShapeImageView_border_color, mBorderColor);
        a.recycle();
    }

    /**
     * 对于普通的view,在执行到onDraw()时,背景图已绘制完成
     * <p/>
     * 对于ViewGroup,当它没有背景时直接调用的是dispatchDraw()方法, 而绕过了draw()方法,
     * 当它有背景的时候就调用draw()方法,而draw()方法里包含了dispatchDraw()方法的调用,
     */
    @Override
    public void onDraw(Canvas canvas) {

        if (getDrawable() != null) {
            if (mShape == SHAPE_CIRCLE) {
                canvas.drawCircle(getWidth() / 2, getHeight() / 2,
                        Math.min(getWidth(), getHeight()) / 2, mBitmapPaint);
            } else if (mShape == SHAPE_OVAL) {
                canvas.drawOval(mViewRect, mBitmapPaint);
            } else {
                canvas.drawRoundRect(mViewRect, mRoundRadius, mRoundRadius, mBitmapPaint);
            }
        }


        if (mBorderSize > 0) { // 绘制边框
            if (mShape == SHAPE_CIRCLE) {
                canvas.drawCircle(mViewRect.right / 2, mViewRect.bottom / 2,
                        Math.min(mViewRect.right, mViewRect.bottom) / 2 - mBorderSize / 2, mBorderPaint);
            } else if (mShape == SHAPE_OVAL) {
                canvas.drawOval(mBorderRect, mBorderPaint);
            } else {
                canvas.drawRoundRect(mBorderRect, mRoundRadius, mRoundRadius, mBorderPaint);
            }
        }
    }

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

    // 不能在onLayout()调用invalidate(),否则导致绘制异常。(setupBitmapShader()中调用了invalidate())
    @Override
    protected void onLayout(boolean changed, int left, int top, int right,
                            int bottom) {
        super.onLayout(changed, left, top, right, bottom);
//        initRect();
//        setupBitmapShader();
    }

    private void setupBitmapShader() {
        // super(context, attrs, defStyle)调用setImageDrawable时,成员变量还未被正确初始化
        if (mBitmapPaint == null) {
            return;
        }
        if (mBitmap == null) {
            invalidate();
            return;
        }
        mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        mBitmapPaint.setShader(mBitmapShader);

        // 固定为CENTER_CROP,使图片在view中居中并裁剪
        mShaderMatrix.set(null);
        // 缩放到高或宽 与view的高或宽 匹配
        float scale = Math.max(getWidth() * 1f / mBitmap.getWidth(), getHeight() * 1f / mBitmap.getHeight());
        // 由于BitmapShader默认是从画布的左上角开始绘制,所以把其平移到画布中间,即居中
        float dx = (getWidth() - mBitmap.getWidth() * scale) / 2;
        float dy = (getHeight() - mBitmap.getHeight() * scale) / 2;
        mShaderMatrix.setScale(scale, scale);
        mShaderMatrix.postTranslate(dx, dy);
        mBitmapShader.setLocalMatrix(mShaderMatrix);
        invalidate();
    }

    // 设置图片的绘制区域
    private void initRect() {

        mViewRect.top = 0;
        mViewRect.left = 0;
        mViewRect.right = getWidth(); // 宽度
        mViewRect.bottom = getHeight(); // 高度

        // 边框的矩形区域不能等于ImageView的矩形区域,否则边框的宽度只显示了一半
        mBorderRect.top = mBorderSize / 2;
        mBorderRect.left = mBorderSize / 2;
        mBorderRect.right = getWidth() - mBorderSize / 2;
        mBorderRect.bottom = getHeight() - mBorderSize / 2;
    }

    public int getShape() {
        return mShape;
    }

    public void setShape(int shape) {
        mShape = shape;
    }

    public float getBorderSize() {
        return mBorderSize;
    }

    public void setBorderSize(int mBorderSize) {
        this.mBorderSize = mBorderSize;
        mBorderPaint.setStrokeWidth(mBorderSize);
        initRect();
        invalidate();
    }

    public int getBorderColor() {
        return mBorderColor;
    }

    public void setBorderColor(int mBorderColor) {
        this.mBorderColor = mBorderColor;
        mBorderPaint.setColor(mBorderColor);
        invalidate();
    }

    public float getRoundRadius() {
        return mRoundRadius;
    }

    public void setRoundRadius(float mRoundRadius) {
        this.mRoundRadius = mRoundRadius;
        invalidate();
    }
}



 res/values/attrs.xml
<declare-styleable name="ShapeImageView">
        <attr name="shape" format="enum">
            <enum name="rect" value="1"/>
            <enum name="circle" value="2"/>
            <enum name="oval" value="3"/>
        </attr>
        <attr name="round_radius" format="dimension"/>
        <attr name="border_size" format="dimension"/>
        <attr name="border_color" format="color"/>
    </declare-styleable>


相关代码我放在了github上:https://github.com/1993hzw/Androids , 接下来的项目代码我都会放在上面,争取做一个类型工具的库。

关于自定义样式的使用,我将在下一节用这个例子说明。

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012964944/article/details/50548720
个人分类: android
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

Android自定义View——可设置形状(圆形、圆角矩形、椭圆)的ImageView,抗锯齿

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭