创建一个简单的圆角ImageView

需求:创建一个简单的圆角ImageView,使左上角,右上角的边缘变成圆角.

public class CornerImageView extends ImageView {
    int radius = 10;//圆角半径
    float density = getResources().getDisplayMetrics().density;//屏幕密度
        public CornerImageView(Context context) {
        super(context);
    }

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

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

    //重写onDraw方法
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int width = getLayoutParams().width;
        int height = getLayoutParams().height;
        //创建矩形区域
        RectF oval = new RectF();
        oval.left = 0 - radius;
        oval.top = 0 - radius;
        oval.bottom = oval.top + radius * 2;
        oval.right = oval.left + radius * 2;
        //创建画笔
        Paint paint = new Paint();

        paint.setStrokeWidth(0.5f * density);
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(Color.parseColor("#F6F6F6"));

        canvas.drawLine(0.5f, 0, 0.5f, height, paint);//左侧竖线
        canvas.drawLine(width - 0.5f, 0, width - 0.5f, height, paint);//右侧竖线
        canvas.drawLine(0, 0.5f, width, 0.5f, paint);//顶部横线
        canvas.drawLine(0, height, width, height, paint);//底部横线

        paint.setColor(Color.WHITE);
    //绘制左上角圆角.颜色为白色.
        for (; oval.left < 0; ) {
            oval.left += 0.1;
            oval.top += 0.1;
            oval.bottom += 0.1;
            oval.right += 0.1;
            canvas.drawArc(oval, 180, 90, false, paint);
        }
    //最后一根弧线为灰色
        paint.setColor(Color.parseColor("#F6F6F6"));
        canvas.drawArc(oval, 180, 90, false, paint);
    //重设矩形区域为ImageView右上角,中心点为矩形右上角
        oval.left = width - radius;
        oval.top = 0 - radius;
        oval.right = oval.left + radius * 2;
        oval.bottom = oval.top + radius * 2;
        paint.setColor(Color.WHITE);
    //绘制右上角弧形区域.
        for (; oval.right > width; ) {
            oval.left -= 0.1;
            oval.top += 0.1;
            oval.bottom += 0.1;
            oval.right -= 0.1;
            canvas.drawArc(oval, -90, 90, false, paint);
        }
    //绘制最后一根弧线
        paint.setColor(Color.parseColor("#F6F6F6"));
        canvas.drawArc(oval, -90, 90, false, paint);

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值