【问题标题】:Android shape drawable color is displayed incorrectlyAndroid 形状可绘制颜色显示不正确
【发布时间】:2017-08-02 22:04:15
【问题描述】:

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

【问题讨论】:

  • 您能否发布输出以及您期望的颜色是什么
  • 它显示圆形的随机颜色,如果您在形状中不添加实体项,则输出相同
  • 所以你说的是红色椭圆形你得到随机颜色?我不这么认为可能是你再次设置背景有问题,除非它应该是红色的
  • 除非您碰巧只复制了其中的一部分,否则您的形状 XML 文件无效,因为 &lt;shape&gt; 标记未关闭。

标签: android android-layout android-shapedrawable


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-12
    • 2022-01-14
    • 2020-12-09
    • 1970-01-01
    相关资源
    最近更新 更多