如何制作带圆角的ImageView?

在Android中,ImageView默认是矩形。 我怎样才能在ImageView中使它成为一个圆角矩形(将我的Bitmap的所有4个角落裁剪成圆角矩形)?


这是相当晚的回应,但对于正在寻找这个的其他人,您可以执行以下代码来手动调整图像的角点。

http://www.ruibm.com/?p=184

这不是我的代码,但我已经使用它,它的功能非常好。 我使用它作为ImageHelper类中的助手,并将其扩展了一点,以传递给定图像所需的羽化量。

最终的代码如下所示:

package com.company.app.utils;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Bitmap.Config;
import android.graphics.PorterDuff.Mode;

public class ImageHelper {
    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels) {
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap
                .getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        final float roundPx = pixels;

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);

        return output;
    }
}

希望这可以帮助别人!


尽管上述答案有效,但Romain Guy(一位核心Android开发人员)在他的博客中展示了一种更好的方法,该方法使用着色器而不是创建位图副本,从而减少内存使用量。 功能的一般要点在这里:

BitmapShader shader;
shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);

Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setShader(shader);

RectF rect = new RectF(0.0f, 0.0f, width, height);

// rect contains the bounds of the shape
// radius is the radius in pixels of the rounded corners
// paint contains the shader that will texture the shape
canvas.drawRoundRect(rect, radius, radius, paint);

这比其他方法的优点是它:

  • 不会创建位图的单独副本,该位图使用大量图像的内存[vs大多数其他答案]
  • 支持反锯齿 [vs clipPath方法]
  • 支持alpha [vs xfermode + porterduff方法]
  • 支持硬件加速 [vs clipPath method]
  • 画一次到画布 [vs xfermode和clippath方法]
  • 我创建了一个基于此代码的RoundedImageView,将此逻辑封装到ImageView中,并添加了适当的ScaleType支持和可选的圆角边框。


    在支持库的v21中现在有一个解决方案:它被称为RoundedBitmapDrawable。

    它基本上就像一个普通的Drawable,除了你给剪裁的角半径:

    setCornerRadius(float cornerRadius)
    

    所以,从Bitmap src和一个目标ImageView ,它看起来像这样:

    RoundedBitmapDrawable dr = RoundedBitmapDrawableFactory.create(res, src);
    dr.setCornerRadius(cornerRadius);
    imageView.setImageDrawable(dr);
    
    链接地址: http://www.djcxy.com/p/5309.html

    上一篇: How to make an ImageView with rounded corners?

    下一篇: Angular Universal does not render index.html