Programmatically create ShapeDrawable

China☆狼群 提交于 2019-12-10 01:23:18

问题


I'm trying to programmatically create a ShapeDrawable but the following code doesn't show anything.

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

I can get it working with 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);

But I would like to create it programmatically. The xml works perfectly so the problem can't be with the ImageView, it must be in creating the ShapeDrawable.


回答1:


Use setIntrinsicWidth and setIntrinsicHeight instead of setBounds to set the width and height.

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:


You might need to create a Class extending ShapeDrawable to override onDraw and then create an instance of your class.

Example: (Source - check link for full example)

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


来源:https://stackoverflow.com/questions/34642224/programmatically-create-shapedrawable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!