Android ImageView 如何實(shí)現(xiàn)圓角

小樊
352
2024-06-14 21:54:36

  1. 使用xml文件設(shè)置圓角屬性:

在res/drawable文件夾下創(chuàng)建一個(gè)xml文件,例如rounded_image.xml,并添加以下代碼:

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#FFFFFF" />
    <corners android:radius="20dp" />
</shape>

然后在布局文件中的ImageView中設(shè)置background為rounded_image.xml即可實(shí)現(xiàn)圓角效果。

  1. 使用Glide或Picasso庫(kù)加載圖片并設(shè)置圓角:

在使用Glide或Picasso加載圖片時(shí),可以使用Transform方法來(lái)實(shí)現(xiàn)圓角效果,例如:

// 使用Glide庫(kù)加載圖片并設(shè)置圓角
Glide.with(context)
    .load(imageUrl)
    .transform(new RoundedCorners(20))
    .into(imageView);
  1. 使用BitmapShader和Bitmap創(chuàng)建圓角圖片:

可以通過(guò)創(chuàng)建一個(gè)自定義的Bitmap對(duì)象,并使用BitmapShader來(lái)實(shí)現(xiàn)圓角效果,例如:

// 創(chuàng)建一個(gè)Bitmap對(duì)象
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);

// 創(chuàng)建一個(gè)BitmapShader對(duì)象
BitmapShader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);

// 創(chuàng)建一個(gè)Paint對(duì)象
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setShader(shader);

// 創(chuàng)建一個(gè)矩形對(duì)象
RectF rect = new RectF(0, 0, bitmap.getWidth(), bitmap.getHeight());

// 創(chuàng)建一個(gè)Bitmap對(duì)象并繪制圓角圖片
Bitmap roundedBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(roundedBitmap);
canvas.drawRoundRect(rect, 20, 20, paint);

// 將Bitmap對(duì)象設(shè)置到ImageView中顯示
imageView.setImageBitmap(roundedBitmap);

以上是三種實(shí)現(xiàn)Android ImageView圓角效果的方法,可以根據(jù)具體需求選擇合適的方法來(lái)實(shí)現(xiàn)。

0