android 自定义View开发实战(四) 圆角矩形ImageView实现

1 前言

有时项目中用ImageView显示图片时需要把形状显示成圆角矩形。因为直角的太生硬了,体验不太友好。为此我们可以自定义一个ImageView来实现。

2 思路

我们自定义一个RoundCornerImageView类继承ImageView,通过改变在onDraw()方法中改变最终绘制的形状。

3 实现

下面直接上代码:
xml,attrs.xml:

    <declare-styleable name="RoundCornerImageView">
        <attr name="corner_size" format="integer" />
    </declare-styleable>

java:

public class RoundCornerImageView extends ImageView {
    private int cornerSize;//圆角大小

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

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

    public RoundCornerImageView(Context context, AttributeSet attrs,int defStyle){
        super(context,attrs,defStyle);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RoundCornerImageView,defStyle,0);
        cornerSize = a.getInt(R.styleable.RoundCornerImageView_corner_size,5);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Path path = new Path();
        int w = getWidth();
        int h = getHeight();
        //这里对path添加一个圆角区域,这里一般需要将dp转换为pixel
        path.addRoundRect(new RectF(0,0,w,h), DensityUtil.dip2px(cornerSize),DensityUtil.dip2px(cornerSize), Path.Direction.CW);
        canvas.clipPath(path);//将Canvas按照上面的圆角区域截取
        super.onDraw(canvas);
    }

    /**
     * 设置圆角的大小
     * @param size
     */
    public void setCornerSize(int size){
        cornerSize = size;
    }
}

4 使用

使用很简单,这里分为java代码中了xml中

java代码:

 private RoundCornerImageView imageView;
 imageView = new RoundCornerImageView(context);
 mageView.setScaleType(ImageView.ScaleType.FIT_XY);
 imageView.setCornerSize(10);
 imageView.setImageResource(xxx);

xml中:

 <xxx.xxx.RoundCornerImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" 
            app:corner_size="10"/>

注意,需要引入相应的命名空间

xmlns:app="http://schemas.android.com/apk/res-auto"
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值