如何在android中通过代码创建Drawables?

时间:2013-02-23 05:03:06

标签: android android-drawable

我想用java代码创建一个简单的蓝色Drawable。我不想在res / drawable文件夹中添加“蓝色”图像。我该如何实现这一目标?我需要在ImageView中将这个drawable用作图像。

enter image description here

2 个答案:

答案 0 :(得分:5)

只需使用BitmapDrawable,即可将Bitmap设置为源。您可以使用许多函数轻松创建位图,例如:

Bitmap myBitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
myBitmap.setPixel(x, y, Color.BLUE);

如果您想要纯色,可以使用该像素创建1x1位图,并根据需要进行缩放。

或者,如果您想要更多灵活性,可以使用Canvas,它允许您使用更多绘图方法(对于矩形,圆形,文本等)。

答案 1 :(得分:1)

或者你可以用XML定义一个ShapeDrawable(是的,我知道你想在代码中做到这一点,但也许这对你也有用):

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <size
        android:width="150dp"
        android:height="150dp" />
    <solid
        android:color="#ff0000ff" />
</shape>

XML可以轻松支持多个屏幕(屏幕分辨率,屏幕密度,外形尺寸,方向)。有关如何定义形状的更多信息,请参见here