在Android中,可以通过自定义ImageView来实现圆角效果,并且可以动态设置圆角大小。下面是一个实现的示例:

  1. 创建一个自定义的圆角ImageView类,继承自ImageView:
public class RoundedCornerImageView extends AppCompatImageView {
    private float cornerRadius;

    public RoundedCornerImageView(Context context) {
        super(context);
        init(context, null);
    }

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

    public RoundedCornerImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        if (attrs != null) {
            TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RoundedCornerImageView);
            cornerRadius = a.getDimension(R.styleable.RoundedCornerImageView_cornerRadius, 0);
            a.recycle();
        }
    }

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

    public void setCornerRadius(float cornerRadius) {
        this.cornerRadius = cornerRadius;
        invalidate();
    }
}
  1. 在res/values/attrs.xml中添加自定义属性:
<resources>
    <declare-styleable name="RoundedCornerImageView">
        <attr name="cornerRadius" format="dimension" />
    </declare-styleable>
</resources>
  1. 在布局文件中使用自定义的圆角ImageView,并通过cornerRadius属性设置圆角大小:
<com.example.RoundedCornerImageView
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:src="@drawable/image"
    app:cornerRadius="20dp" />
  1. 在代码中可以通过调用setCornerRadius()方法动态设置圆角大小:
RoundedCornerImageView imageView = findViewById(R.id.imageView);
imageView.setCornerRadius(30);

这样就实现了一个自定义的圆角ImageView,并且可以通过代码动态设置圆角大小


原文地址: https://www.cveoy.top/t/topic/ik0m 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录