Bitmap dans ImageView avec des coins arrondis

j'ai un ImageView et je veux le faire avec rounded corners .

j'utilise ceci:

<?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>

et définissez ce code comme arrière-plan de mon imageview. Cela fonctionne, mais l'image src que j'ai mise sur le ImageView sort des frontières et ne s'adapte pas à la nouvelle forme.

comment résoudre le problème?

44
demandé sur kId 2013-08-14 14:32:21

10 réponses

essayez celui-ci :

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

et

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

ou,

ImageView iv= new CustomImageView(this);
iv.setImageResource(R.drawable.pic);
78
répondu Anand 2014-02-27 08:35:38

faire une fonction qui fait arrondi à votre bitmap en utilisant la toile.

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

pour plus d'informations: > ici

17
répondu Ketan Ahir 2017-05-23 12:26:18

il est étrange que personne ici n'a mentionné RoundedBitmapDrawable de la bibliothèque de Soutien Android v4. Pour moi, c'est le moyen le plus simple d'obtenir des coins arrondis sans frontières. Voici un exemple d'usage:

RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), bitmap);
final float roundPx = (float) bitmap.getWidth() * 0.06f;
roundedBitmapDrawable.setCornerRadius(roundPx);
17
répondu lobzik 2015-11-13 17:06:10

la réponse acceptée utilise la coupure de chemin, mais elle ne supporte pas l'anti-aliasing. Voir Romain Guy de commentaires sur son post. "clipping path ne supporte pas l'antialiasing et vous obtenez des bords dentelés."

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

il y a une bonne bibliothèque(RoundedImageView de vinc3m1) qui supporte les coins arrondis sur ImageView, mais elle ne supporte que les même les rayons sur tous les coins. Donc j'en ai fait un que vous pouvez placer des rayons différents sur chaque coin.

il ne s'appuie pas sur la Coupe de chemin, ni redessiner. Il ne tire qu'une seule fois avec la méthode canvas.drawPath() . Donc j'ai finalement obtenu le résultat que je voulais comme ci-dessous.

enter image description here

voir: https://github.com/pungrue26/SelectableRoundedImageView

9
répondu 김준호 2014-12-14 13:12:54

si vous avez besoin de bordure aussi, vous pouvez utiliser une image de boîte arrondie avec le corps transparent et blanc de côté.Par Exemple:

Rounded box

et utilisez ceci avec l'image cible comme ci-dessous:

<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" />

Merci!

4
répondu Kalu Khan Luhar 2014-01-09 11:27:49

si vous avez besoin de faire Bitmap avec des rayons de coin différents et je recommande le code suivant:

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;
}
3
répondu Sergei Vasilenko 2016-03-21 13:46:03

pour moi la méthode ci-dessous fait la magie. :) Cette méthode accepte un objet bitmap et le renvoie avec des coins arrondis. roundPx est le nombre de pixels arrondis que vous voulez:

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

...ou vous pouvez utiliser cette" bibliothèque au lieu de ImageView sans autre codage.

2
répondu Niamatullah Bakhshi 2018-08-01 15:31:38
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);

    }

}
0
répondu carlosgpn 2014-02-17 15:03:28

la méthode pour faire des coins arrondis pour imageview dans android n'est pas les gars de la science de fusée! il suffit d'utiliser un png avec les courbes requises avec la même couleur que votre arrière-plan et de définir la superposition à FITXY.!

-1
répondu Neeraj Manoharan 2014-02-17 10:50:42
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);
    }

}
-3
répondu Prashant 2015-01-28 10:24:10