首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >以编程方式创建ShapeDrawable

以编程方式创建ShapeDrawable
EN

Stack Overflow用户
提问于 2016-01-07 04:32:49
回答 2查看 12.1K关注 0票数 13

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

代码语言:javascript
复制
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一起工作。

代码语言:javascript
复制
<?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时。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-01-07 09:07:07

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

代码语言:javascript
复制
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);
票数 13
EN

Stack Overflow用户

发布于 2016-01-07 04:47:36

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

示例:(完整示例的Source- check链接)

代码语言:javascript
复制
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);
            }
        }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34642224

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档