位图中的ImageView与圆角图中、圆角、ImageView

2023-09-05 05:57:17 作者:白衣影眠梦

我有一个ImageView的,我想用使圆角

I have an ImageView and I want to make it with rounded corners.

我用这样的:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> 
    <solid  android:color="@null"/>    

    <stroke android:width="1dp"
            android:color="#ff000000"/>


    <corners android:radius="62px"/> 
</shape>

和设置该code作为我的ImageView的背景。 它的工作原理,但我穿上的ImageView 的SRC图像是走出去的边界,也不适应自己变成新的形状。

And set this code as background of my imageview. It works, but the src image that I put on the ImageView is going out of the borders and doesn't adapt itself into the new shape.

我该如何解决这个问题呢?

How can I solve the problem?

推荐答案

试试这个:

public class CustomImageView extends ImageView {

    public static float radius = 18.0f;  

    public CustomImageView(Context context) {
        super(context);
    }

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

    public CustomImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        //float radius = 36.0f;  
        Path clipPath = new Path();
        RectF rect = new RectF(0, 0, this.getWidth(), this.getHeight());
        clipPath.addRoundRect(rect, radius, radius, Path.Direction.CW);
        canvas.clipPath(clipPath);
        super.onDraw(canvas);
    }
}

<your.pack.name.CustomImageView
                android:id="@+id/selectIcon"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:scaleType="centerCrop" />

CustomImageView  iconImage = (CustomImageView )findViewById(R.id.selectIcon);
iconImage.setImageBitmap(bitmap);

ImageView iv= new CustomImageView(this);
iv.setImageResource(R.drawable.pic);