android 自定义View开发实战(四) 圆角矩形ImageView实现
16lz
2021-01-24
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.RoundCornerImageView android:layout_width="wrap_content" android:layout_height="wrap_content" app:corner_size="10"/>
注意,需要引入相应的命名空间
xmlns:app="http://schemas.android.com/apk/res-auto"
更多相关文章
- android listView滚动时隔行出现黑色分割线
- 全面了解Android热修复技术
- Flutter(三):实现Flutter代码调用Android原生代码(创建WebView Plu
- Android(安卓)配置PhoneGap开发环境
- 关于Android(安卓)Force Close 出现的原因 以及解决方法
- android.graphics.Movie
- MVP+RxJava+Dagger打造的Android(安卓)Album
- 【QQ登录】Android_SDK使用说明
- Android(安卓)O 新特性介绍:自适应图标(Adaptive Icons)