我需要有弯曲角的方形图像视图。一切似乎都很好,IntelliJ Idea 的预览显示它工作正常。但是,当我在真实设备上运行它时,角落不是曲线。
我的自定义图像视图:
public class SquareImageView extends ImageView {
private static final String TAG = "SquareImageView";
public SquareImageView(Context context) {
super(context);
}
public SquareImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SquareImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int h = this.getMeasuredHeight();
int w = this.getMeasuredWidth();
setMeasuredDimension(w, w);
}
@Override
protected void onDraw(Canvas canvas) {
Path clipPath = new Path();
float radius = 20.0f;
float padding = radius / 2;
int w = this.getWidth();
int h = this.getHeight();
clipPath.addRoundRect(new RectF(padding, padding, w - padding, h - padding), radius, radius, Path.Direction.CW);
canvas.clipPath(clipPath);
canvas.drawColor(Color.RED);
super.onDraw(canvas);
}
}
布局的 XML:
<com.belldigital.widget.SquareImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/ivProfilePicture"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_alignParentTop="true"
android:adjustViewBounds="true"
android:scaleType="fitXY"
android:background="@color/Black"
android:contentDescription="@string/general_content_description"
android:src="@drawable/ic_default_logo"
android:layout_marginTop="@dimen/side_margin"/>
模拟器截图:
真机截图: