先上图,上半部分是矩形、下半部分是弧形,如图所示:
上图是实现的效果,在实现弧形ImageView后用Glide的BlurTransformation添加了高斯模糊,这种弧形图片一般都像这样用于个人中心或者用户中心顶部。
第一步:绘制图中形状的ImageView
1、设置Path
Path path = new Path();
path.moveTo(0, 0);
path.lineTo(0, getHeight() / 3 * 2);
path.quadTo(getWidth() / 2, getHeight() / 3 * 2 + 2 * mArcHeight, getWidth(), getHeight() / 3 * 2);
path.lineTo(getWidth(), 0);
path.close();
复制代码
2、裁剪图片
/*
下边这行代码防锯齿,在没有Paint的情况下使用,但感觉没什么卵用,后期改进
*/
canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG));
canvas.clipPath(path);
super.onDraw(canvas);//注意此行代码的位置
复制代码
备注:如注释所示,设置防锯齿后还是有锯齿感,希望知道原因或者有解决办法的大佬帮忙看看。
主要就是一个路径绘制和画布裁剪,附上全部代码:
public class ArcImageView extends AppCompatImageView {
/*
*弧形高度
*/
private int mArcHeight;
private static final String TAG = "ArcImageView";
public ArcImageView(Context context) {
this(context, null);
}
public ArcImageView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public ArcImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ArcImageView);
mArcHeight = typedArray.getDimensionPixelSize(R.styleable.ArcImageView_arcHeight, 0);
}
@Override
protected void onDraw(Canvas canvas) {
Path path = new Path();
path.moveTo(0, 0);
path.lineTo(0, getHeight() / 3 * 2);
path.quadTo(getWidth() / 2, getHeight() / 3 * 2 + 2 * mArcHeight, getWidth(), getHeight() / 3 * 2);
path.lineTo(getWidth(), 0);
path.close();
/*
下边这行代码防锯齿,在没有Paint的情况下使用,但感觉没什么卵用,后期改进
*/
canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG));
canvas.clipPath(path);
super.onDraw(canvas);
}
}
复制代码
Attribute属性:
<attr name="arcHeight" format="dimension"/>
<declare-styleable name="ArcImageView">
<attr name="arcHeight"/>
</declare-styleable>
复制代码
第二步:使用这个自定义ImageView
<packagename.ArcImageView
android:id="@+id/iv_head_bg"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:arcHeight="@dimen/space_55"
android:scaleType="centerCrop"
android:src="@color/mainYellow"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
复制代码
第三步:添加高斯模糊
1、引入Glide
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'jp.wasabeef:glide-transformations:2.0.0'
复制代码
2、添加高斯模糊
ArcImageView ivHeadBg = helper.getView(R.id.iv_head_bg);
Glide.with(mContext)
.load(url)
.dontAnimate()
.error(R.drawable.icon_default_head)
//设置高斯模糊
.bitmapTransform(new BlurTransformation(mContext, 14, 3))
.into(ivHeadBg);
复制代码
由于还得赶项目,时间匆忙,回头整理成一个小Demo发出来。