0

我正在尝试绘制一个简单的圆圈并将其用作 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"/>
4

1 回答 1

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 制作成圆形。

于 2017-03-15T09:55:01.683 回答