以编程方式创建ShapeDrawable [英] Programmatically create ShapeDrawable

查看:71
本文介绍了以编程方式创建ShapeDrawable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我可以在xml中使用它.

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

但是我想以编程方式创建它.xml可以完美运行,因此问题不会出在ImageView上,而必须在创建ShapeDrawable时出现.

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.

推荐答案

使用 setIntrinsicWidth 而不是 setBounds 来设置宽度和高度.

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

这篇关于以编程方式创建ShapeDrawable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆