chromelend
chromelend

Reputation: 295

Rounded corner ImageView - Android

I try to create imageview with rounded corners.i searched and found xml code

<?xml version="1.0" encoding="utf-8"?>

<solid android:color="#00ffffff" />

<padding
    android:bottom="6dp"
    android:left="6dp"
    android:right="6dp"
    android:top="6dp" />

<corners android:radius="12dp" />

<stroke
    android:width="6dp"
    android:color="#ffffffff" />

and this is a my imageview xml code

<ImageView
                android:id="@+id/slidemenuuserimage"
                android:layout_width="90dp"
                android:layout_height="90dp"
                android:layout_alignParentBottom="true"
                android:layout_alignParentLeft="true"
                android:layout_marginBottom="16dp"
                android:layout_marginLeft="14dp"
                android:background="@drawable/frame" />

i have one problem.when i added background image programmatically i receive divirent result.

slidemenuuserimage=(ImageView)findViewById(R.id.slidemenuuserimage);
    slidemenuuserimage.setBackgroundResource(R.drawable.myuserimg);

this is a my result enter image description here

how i can add padding left or right programmatically.in my option this is a my problem if anyone knows solution please help me

Upvotes: 3

Views: 14471

Answers (3)

Leonidos
Leonidos

Reputation: 10518

you need to set src image, not background. So use setImageResource() not setBackgroundResource()

Upvotes: -2

Murtaza Khursheed Hussain
Murtaza Khursheed Hussain

Reputation: 15336

You can also do this programatically

public Bitmap roundCornerImage(Bitmap raw, float round) {
  int width = raw.getWidth();
  int height = raw.getHeight();
  Bitmap result = Bitmap.createBitmap(width, height, Config.ARGB_8888);
  Canvas canvas = new Canvas(result);
  canvas.drawARGB(0, 0, 0, 0);

  final Paint paint = new Paint();
  paint.setAntiAlias(true);
  paint.setColor(Color.parseColor("#000000"));

  final Rect rect = new Rect(0, 0, width, height);
  final RectF rectF = new RectF(rect);

  canvas.drawRoundRect(rectF, round, round, paint);

  paint.setXfermode(new PorterDuffXfermode(Mode.raw_IN));
  canvas.drawBitmap(raw, rect, rect, paint);

  return result;
 }

Use it like

slidemenuuserimage.setImageBitmap(roundCornerImage(BitmapFactory.decodeResource(getResources(), R.drawable.yourImage),50)

Upvotes: 7

Skizo-ozᴉʞS ツ
Skizo-ozᴉʞS ツ

Reputation: 20616

Try out this shape

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

    <stroke android:width="3dp"
            android:color="#ffffffff"/>

    <padding android:left="1dp"
             android:top="1dp"
             android:right="1dp"
             android:bottom="1dp"/> 

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

Code is here

Upvotes: 2

Related Questions