Android形状可绘制颜色显示不正确

时间:2017-03-12 23:12:54

标签: android android-layout android-shapedrawable

我试图绘制一个简单的圆圈并将其用作ImageView的背景,问题是每当我打开应用程序时,圆圈都会以不同的颜色绘制,这是我的代码。

<?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="oval">

    <size
        android:width="16dp"
        android:height="16dp"
    />


    <solid android:color="#FFF6621F"/>

    <ImageView
        android:id="@+id/counterBackground"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/shape_circle"/>

1 个答案:

答案 0 :(得分:0)

您可以使用以下代码....

activity_main.xml中

<LinearLayout
     android:layout_width="300dp"
     android:layout_height="300dp"
     android:layout_gravity="center">

         <ImageView
              android:id="@+id/imgview"
              android:layout_width="match_parent"
              android:layout_height="match_parent" />

</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    ImageView imgview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imgview = (ImageView) findViewById(R.id.imgview);

        Bitmap bm = BitmapFactory.decodeResource(getResources(),
                R.drawable.ic_blogger);

        imgview.setImageBitmap(getCircleBitmap(bm));

    }

    private Bitmap getCircleBitmap(Bitmap bitmap) {
        final Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        final Canvas canvas = new Canvas(output);

        final int color = Color.RED;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawOval(rectF, paint);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);

        bitmap.recycle();
        return output;
    }
}

您可以使用getCircleBitmap()方法将ImageView设置为圆形。