轻松实现圆角图片

来源:互联网 发布:网络设计是什么级别 编辑:程序博客网 时间:2024/06/05 19:27

轻松实现圆角图片

圆角图片需求很多,教程也很多,本篇博客记录一下实现的步骤,只需要几十行代码即可轻松实现。

实现步骤:

  • 1,使用BitmapShader给画笔着色
  • 2,绘制圆

效果图:
此处输入图片的描述

使用BitmapShader给画笔着色

BitmapShader给画笔着色就是用 Bitmap 的像素来作为图形或文字的填充
代码类似于这样的

Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);Bitmap mBitmap = drawableToBitmap(getDrawable());BitmapShader mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);mPaint.setShader(mBitmapShader);

效果图来自这里,非常感谢HenCoder
图片

构造方法:

BitmapShader(Bitmap bitmap, Shader.TileMode tileX, Shader.TileMode tileY)

参数:
bitmap:用来做模板的 Bitmap 对象
tileX:横向的 TileMode
tileY:纵向的 TileMode。

CLAMP:

此处输入图片的描述

MIRROR:

此处输入图片的描述

REPEAT:

此处输入图片的描述

绘制圆

代码类似于

@Override    protected void onDraw(Canvas canvas) {        if (getDrawable() != null) {            canvas.drawCircle(radius, radius, radius, mPaint);        }    }

完整代码,注释比较详细,或者点击这里

public class RoundImageView extends ImageView {    private Paint mPaint;//绘制圆的画笔    private int radius;//绘制圆的半径    public RoundImageView(Context context) {        this(context, null);    }    public RoundImageView(Context context, AttributeSet attrs) {        this(context, attrs, 0);    }    public RoundImageView(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);//初始化画笔    }    /**     * Drawable 转Bitmap     *     * @param drawable     * @return     */    private Bitmap drawableToBitmap(Drawable drawable) {        if (drawable instanceof BitmapDrawable) {            return ((BitmapDrawable) drawable).getBitmap();        } else {            int width = drawable.getIntrinsicWidth();            int height = drawable.getIntrinsicHeight();            Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);            Canvas mCanvas = new Canvas(bitmap);            drawable.draw(mCanvas);            return bitmap;        }    }    @Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        super.onMeasure(widthMeasureSpec, heightMeasureSpec);//这里是为了能够通过getMeasuredWidth拿到具体测量值,先调用一下super        int width = getMeasuredWidth();        int height = getMeasuredHeight();        int requireSize = Math.min(width, height);        radius = requireSize / 2;//半径就是宽高的一半        setMeasuredDimension(requireSize, requireSize);//强制宽高一致    }    @Override    protected void onDraw(Canvas canvas) {        drawCircle(canvas);    }    /**     * 画圆     * @param canvas     */    private void drawCircle(Canvas canvas) {        if (getDrawable() != null) {            Bitmap mBitmap = drawableToBitmap(getDrawable());            BitmapShader mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);            mPaint.setShader(mBitmapShader);//画笔着色            canvas.drawCircle(radius, radius, radius, mPaint);        }    }}

总结

看完hencoder的博客,学习了很多之前忽略的知识,算是一个对于基础的非常好的完善,感谢这些乐于分享的前辈们。

原创粉丝点击