圆角ImageView - Android

时间:2015-02-03 10:56:18

标签: android android-imageview rounded-corners

我尝试使用圆角创建imageview。搜索并找到xml代码

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

这是我的imageview xml代码

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

我有一个问题。当我以编程方式添加背景图像时,我会收到divirent结果。

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

这是我的结果 enter image description here

我如何以编程方式向左或向右添加填充。在我的选项中,这是我的问题 如果有人知道解决方案,请帮助我

3 个答案:

答案 0 :(得分:6)

您也可以以编程方式执行此操作

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

一样使用它
slidemenuuserimage.setImageBitmap(roundCornerImage(BitmapFactory.decodeResource(getResources(), R.drawable.yourImage),50)

答案 1 :(得分:2)

试试这个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>

代码为here

答案 2 :(得分:-2)

你需要设置src图像,而不是背景。因此,请使用setImageResource()而不是setBackgroundResource()