如何制作带圆角的 ImageView?

How to make an ImageView with rounded corners?(如何制作带圆角的 ImageView?)

本文介绍了如何制作带圆角的 ImageView?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Android 中,默认情况下 ImageView 是一个矩形.如何在 ImageView 中将其设为圆角矩形(将 Bitmap 的所有 4 个角剪成圆角矩形)?

In Android, an ImageView is a rectangle by default. How can I make it a rounded rectangle (clip off all 4 corners of my Bitmap to be rounded rectangles) in the ImageView?

推荐答案

这已经很晚了,但是对于正在寻找这个的其他人,您可以执行以下代码来手动圆角图像.

This is pretty late in response, but for anyone else that is looking for this, you can do the following code to manually round the corners of your images.

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

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

This isn't my code, but I've used it and it's works wonderfully. I used it as a helper within an ImageHelper class and extended it just a bit to pass in the amount of feathering I need for a given image.

最终代码如下所示:

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;
    }
}

这篇关于如何制作带圆角的 ImageView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何制作带圆角的 ImageView?

基础教程推荐