在 Android 中,可以通过自定义 ImageView 来实现圆形图片的效果。具体实现步骤如下:

  1. 继承 ImageView 类,创建一个 CircleImageView 类。
  2. 在 CircleImageView 类中重写 onDraw() 方法,在其中绘制圆形图片。
  3. 在 CircleImageView 类中添加一个 setBitmap() 方法,用于设置要显示的图片。
  4. 在布局文件中使用 CircleImageView 控件,并调用 setBitmap() 方法设置要显示的图片。

下面是 CircleImageView 类的代码示例:

public class CircleImageView extends ImageView {
    private Bitmap mBitmap;
    private Paint mPaint;
    private RectF mRectF;

    public CircleImageView(Context context) {
        super(context);
        init();
    }

    public CircleImageView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CircleImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mRectF = new RectF();
    }

    public void setBitmap(Bitmap bitmap) {
        mBitmap = bitmap;
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (mBitmap == null) {
            return;
        }

        int width = getWidth();
        int height = getHeight();
        int radius = Math.min(width, height) / 2;
        mRectF.set(0, 0, width, height);

        canvas.save();
        canvas.clipRect(mRectF);
        canvas.drawCircle(radius, radius, radius, mPaint);
        canvas.restore();

        canvas.save();
        canvas.clipRect(mRectF);
        BitmapShader shader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        mPaint.setShader(shader);
        canvas.drawCircle(radius, radius, radius, mPaint);
        canvas.restore();
    }
}

在布局文件中,可以像下面这样使用 CircleImageView 控件:

<com.example.CirclImageView
    android:id="@+id/image_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/my_image" />

在代码中,可以通过调用 setBitmap() 方法设置要显示的图片:

CircleImageView imageView = findViewById(R.id.image_view);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.my_image);
imageView.setBitmap(bitmap);
``

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

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