以编程方式创建ShapeDrawable

15

我正在尝试以编程方式创建ShapeDrawable,但以下代码没有显示任何内容。

ImageView image = new ImageView (context);
image.setLayoutParams (new LayoutParams (200, 200));
ShapeDrawable badge = new ShapeDrawable (new OvalShape());
badge.setBounds (0, 0, 200, 200);
badge.getPaint().setColor(Color.RED);
ImageView image = new ImageView (context);
image.setImageDrawable (badge);
addView (image);

我可以使用 XML 使其正常工作。

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <size
        android:width="200px"
        android:height="200px" />
    <solid
        android:color="#F00" />
</shape>

ImageView image = new ImageView (context);
image.setLayoutParams (new LayoutParams (200, 200));
image.setImageResource (R.drawable.badge);
addView (image);

但我希望能够以编程方式创建它。XML 呈现得非常完美,因此问题肯定不在 ImageView 上,一定是在创建 ShapeDrawable 时出了问题。


1
你尝试设置ImageView的布局边界了吗?请添加您在其中添加ImageView的布局信息。 - David Medenjak
这是什么意思?ImageView image = new ImageView (context); 第二次出现? - The_Martian
2个回答

16

使用setIntrinsicWidthsetIntrinsicHeight来设置宽度和高度,而不是使用setBounds

ImageView image = new ImageView (context);
image.setLayoutParams (new LayoutParams (200, 200));
ShapeDrawable badge = new ShapeDrawable (new OvalShape());
badge.setIntrinsicWidth (200);
badge.setIntrinsicHeight (200);
badge.getPaint().setColor(Color.RED);
image.setImageDrawable (badge);
addView (image);

1
你可能需要创建一个扩展ShapeDrawable的类来覆盖onDraw方法,然后创建该类的实例。
示例:(源代码 - 请查看链接获取完整示例)
private static class MyShapeDrawable extends ShapeDrawable {
            private Paint mStrokePaint = new Paint(Paint.ANTI_ALIAS_FLAG);

            public MyShapeDrawable(Shape s) {
                super(s);
                mStrokePaint.setStyle(Paint.Style.STROKE);
            }

            public Paint getStrokePaint() {
                return mStrokePaint;
            }

            @Override protected void onDraw(Shape s, Canvas c, Paint p) {
                s.draw(c, p);
                s.draw(c, mStrokePaint);
            }
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接