【问题标题】:Programmatically create ShapeDrawable以编程方式创建 ShapeDrawable
【发布时间】:2016-01-06 20:32:48
【问题描述】:

我正在尝试以编程方式创建 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 中。

【问题讨论】:

  • 您是否尝试为您的图像视图设置布局边界?请添加有关您将图像视图添加到的布局的信息
  • 这是什么意思? ImageView 图像 = 新的 ImageView(上下文);第二次?

标签: android drawable


【解决方案1】:

使用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);

【讨论】:

    【解决方案2】:

    您可能需要创建一个扩展 ShapeDrawable 的类来覆盖 onDraw,然后创建您的类的一个实例。

    示例:Source - 查看链接查看完整示例)

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-12
      • 1970-01-01
      • 2017-08-19
      • 2015-09-15
      • 2013-03-28
      • 2013-07-25
      • 2013-07-22
      相关资源
      最近更新 更多