Rounded corner ImageView - Android

痞子三分冷 提交于 2019-11-29 10:27:09

问题


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

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


回答1:


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)



回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/28297164/rounded-corner-imageview-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!