简体   繁体   English

Bitmap in ImageView 带圆角

[英]Bitmap in ImageView with rounded corners

I have an ImageView and I want to make it with rounded corners .我有一个 ImageView,我想把它做成rounded corners

I use this:我用这个:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> 
    <solid  android:color="@null"/>    

    <stroke android:width="1dp"
            android:color="#ff000000"/>


    <corners android:radius="62px"/> 
</shape>

And set this code as background of my imageview. It works, but the src image that I put on the ImageView is going out of the borders and doesn't adapt itself into the new shape.并将此代码设置为我的 imageview 的背景。它可以工作,但我放在ImageView上的 src 图像超出了边界并且无法适应新形状。

How can I solve the problem?我该如何解决这个问题?

try this one :试试这个:

public class CustomImageView extends ImageView {

    public static float radius = 18.0f;  

    public CustomImageView(Context context) {
        super(context);
    }

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

    public CustomImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

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

and

<your.pack.name.CustomImageView
                android:id="@+id/selectIcon"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:scaleType="centerCrop" />

CustomImageView  iconImage = (CustomImageView )findViewById(R.id.selectIcon);
iconImage.setImageBitmap(bitmap);

or,要么,

ImageView iv= new CustomImageView(this);
iv.setImageResource(R.drawable.pic);

It's strange that nobody here has mentioned RoundedBitmapDrawable from Android Support Library v4.奇怪的是,这里没有人提到 Android Support Library v4 中的RoundedBitmapDrawable For me it is the simplest way to get rounded corners without borders.对我来说,这是获得无边界圆角的最简单方法。 Here is example of usage:以下是使用示例:

RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), bitmap);
final float roundPx = (float) bitmap.getWidth() * 0.06f;
roundedBitmapDrawable.setCornerRadius(roundPx);

Make one function which make rounded to your bitmap using canvas.制作一个使用画布四舍五入到位图的函数。

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

for more info:> here欲了解更多信息:> 这里

The accepted answer uses path clipping, but it doesn't support anti-aliasing.接受的答案使用路径裁剪,但不支持抗锯齿。 See Romain Guy's comments on his post.参见 Romain Guy 对他的帖子的评论。 "path clipping does not support antialiasing and you get jagged edges." “路径剪裁不支持抗锯齿,您会看到锯齿状边缘。”

http://www.curious-creature.com/2012/12/11/android-recipe-1-image-with-rounded-corners/ http://www.curious-creature.com/2012/12/11/android-recipe-1-image-with-rounded-corners/

There is one good library(vinc3m1's RoundedImageView) that supoorts rounded corners on ImageView, but it only supports the same radiuses on every corners.有一个很好的库(vinc3m1 的 RoundedImageView)支持 ImageView 上的圆角,但它只支持每个角的相同半径。 So I made one that you can set different radiuses on each corners.所以我做了一个,你可以在每个角落设置不同的半径。

It doesn't rely on path clipping, nor redrawing.它不依赖于路径裁剪,也不依赖于重绘。 It only draws one time with canvas.drawPath() method.它只使用canvas.drawPath()方法绘制一次。 So I finally got result that I wanted like below.所以我终于得到了我想要的结果,如下所示。

在此处输入图片说明

See : https://github.com/pungrue26/SelectableRoundedImageView参见: https : //github.com/punrue26/SelectableRoundedImageView

If you need border also then: 1. You can use a rounded box image with a transparent body and white from outside.如果您还需要边框,则: 1. 您可以使用带有透明主体和外部白色的圆形框图像。 For Example:例如:

圆框

and use this with target image like below:并将其与目标图像一起使用,如下所示:

<FrameLayout
android:layout_width="100px"
android:layout_height="100px" >
<ImageView
        android:id="@+id/targetImage"
        android:layout_width="100px"
        android:layout_height="100px"
        android:src="@drawable/app_icon"
        android:layout_gravity="center" />
<ImageView
        android:id="@+id/boxImage"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scaleType="fitXY"
        android:src="@drawable/box" />

  1. Adding CardView as parent layout of ImageView also be a good solution.添加CardView作为ImageView父布局也是一个很好的解决方案。

If you need make Bitmap with different corner radii and I recommend follow code:如果您需要制作具有不同圆角半径的位图,我建议您遵循以下代码:

private static Bitmap createRoundedRectBitmap(@NonNull Bitmap bitmap,
                                float topLeftCorner, float topRightCorner,
                                float bottomRightCorner, float bottomLeftCorner) {
    Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), 
                                        Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(output);

    final int color = Color.WHITE;
    final Paint paint = new Paint();
    final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
    final RectF rectF = new RectF(rect);
    Path path = new Path();
    float[] radii = new float[]{
            topLeftCorner, bottomLeftCorner,
            topRightCorner, topRightCorner,
            bottomRightCorner, bottomRightCorner,
            bottomLeftCorner, bottomLeftCorner
    };

    paint.setAntiAlias(true);
    canvas.drawARGB(0, 0, 0, 0);
    paint.setColor(color);
    path.addRoundRect(rectF, radii, Path.Direction.CW);
    canvas.drawPath(path, paint);
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    canvas.drawBitmap(bitmap, rect, rect, paint);
    return output;
}

For me, the below method does the magic.对我来说,下面的方法很神奇。 :) This method accepts a bitmap object and returns it back with rounded corners. :) 这个方法接受一个位图对象并用圆角返回它。 roundPx is the number of rounded pixels you want: roundPx是您想要的圆形像素数:

public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
    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 = 12;

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

...or you could use this library instead of ImageView without any further coding. ...或者你可以使用这个库而不是ImageView而无需任何进一步的编码。

It can be done with background drawable, like explain in many posts including this one, but it also needs to set clipping.它可以通过背景可绘制来完成,就像在包括这个在内的许多帖子中解释一样,但它也需要设置剪辑。 Here a full example:这里有一个完整的例子:

The code:代码:

AppCompatImageView iconView = findViewById(R.id.thumbnail);
iconView.setClipToOutline(true);

The layout:布局:

<android.support.v7.widget.AppCompatImageView
    android:id="@+id/thumbnail"
    android:layout_width="80dp"
    android:layout_height="80dp"
    android:contentDescription="@string/thumbnail"
    android:scaleType="centerInside"
    android:background="@drawable/round_view" <!--here set the drawable as background -->
    tools:src="@mipmap/ic_user" />

The drawable:可绘制的:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="10dp" />
</shape>
public class RoundedImageView extends ImageView {

    public RoundedImageView(Context context) {
        super(context);
    }

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

    public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        super.onDraw(canvas);

        Bitmap rounder = Bitmap.createBitmap(getWidth(),getHeight(),Bitmap.Config.ARGB_8888);
        Canvas canvasRound = new Canvas(rounder);    

        Paint xferPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        xferPaint.setColor(Color.BLACK);

        final int rx = this.getWidth(); //our x radius
        final int ry = this.getHeight(); //our y radius

        canvasRound.drawRoundRect(new RectF(0,0,rx,ry), rx, ry, xferPaint);     

        xferPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));

        canvas.drawBitmap(rounder, 0, 0, xferPaint);

    }

}
/**
 * Creates new circular bitmap based on original one.
 * @param newCornerRadius is optional
 */
fun Bitmap.toCircular(context: Context, newCornerRadius: Float? = null): RoundedBitmapDrawable {
    return RoundedBitmapDrawableFactory.create(context.resources, this).apply {
        isCircular = true
        newCornerRadius?.let {
            cornerRadius = it
        }
    }
}

Kotlin version Kotlin版

fun Bitmap.roundCorner(pixels: Int): Bitmap {
        val output: Bitmap = Bitmap.createBitmap(
                width, height, Bitmap.Config.ARGB_8888
        )
        val canvas = Canvas(output)
        val color = -0xbdbdbe
        val paint = Paint()
        val rect = Rect(0, 0, width, height)
        val rectF = RectF(rect)
        val roundPx = pixels.toFloat()
        paint.isAntiAlias = true
        canvas.drawARGB(0, 0, 0, 0)
        paint.color = color
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint)
        paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
        canvas.drawBitmap(this, rect, rect, paint)
        return output
}

call by: sourceBitmap.roundCorner(60)调用方式: sourceBitmap.roundCorner(60)

The method to make rounded corners for imageview in android is not rocket science guys!在android中为imageview制作圆角的方法不是火箭科学家伙! just use a png with required curves with the same color as your background and set the overlay to FITXY.!只需使用具有与背景颜色相同的所需曲线的 png,并将叠加层设置为 FITXY。!

public void drawRoundImage(boolean isEditPicEnable){
   if(originalImageBitmap != null){
        setBackgroundResource(R.drawable.ic_account_user_outer_circle_blue);

        if (isEditPicEnable) {
            setBackgroundResource(R.drawable.ic_account_user_outer_circle_white);
            Bitmap mask = BitmapFactory.decodeResource(getResources(), R.drawable.ic_account_white_mask);
            Bitmap mask1 = BitmapFactory.decodeResource(getResources(), R.drawable.ic_account_pencil_bg);
            originalImageBitmap = Bitmap.createScaledBitmap(originalImageBitmap, mask.getWidth(), mask.getHeight(), true);
            Bitmap result = Bitmap.createBitmap(mask.getWidth(), mask.getHeight(), Bitmap.Config.ARGB_8888);
            Canvas mCanvas = new Canvas(result);
            Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
            mCanvas.drawBitmap(originalImageBitmap, 0, 0, null);
            mCanvas.drawBitmap(mask, 0, 0, paint);
            mCanvas.drawBitmap(mask1, 0, 0, null);
            Bitmap mask2 = BitmapFactory.decodeResource(getResources(), R.drawable.ic_account_pencil);
            mCanvas.drawBitmap(mask2, 0, 0, null);
            setImageBitmap(result);
            setScaleType(ScaleType.FIT_XY);
        } else {
            Bitmap mask = BitmapFactory.decodeResource(getResources(),R.drawable.ic_account_white_mask);
            originalImageBitmap = Bitmap.createScaledBitmap(originalImageBitmap, mask.getWidth(),mask.getHeight(), true);
            Bitmap result = Bitmap.createBitmap(mask.getWidth(), mask.getHeight(),Bitmap.Config.ARGB_8888);
            Canvas mCanvas = new Canvas(result);
            Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
            mCanvas.drawBitmap(originalImageBitmap, 0, 0, null);
            mCanvas.drawBitmap(mask, 0, 0, paint);
            paint.setXfermode(null);
            setImageBitmap(result);
            setScaleType(ScaleType.FIT_XY);
        }

    }else{
        setBackgroundResource(R.drawable.ic_account_user_outer_circle_blue);
        setImageResource(R.drawable.my_ac_default_profile_pic);
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM