在android中创建一个带颜色的图像

eug*_*ene 4 android image colors

设置背景似乎没有给android的大小提供任何提示.
因此,我正在寻找一种创建具有特定颜色的图像的方法.
(如果可以在xml中完成会更好)

在iOS中,这可以通过实现

+ (UIImage*)placeHolderImage
{
    static UIImage* image = nil;
    if(image != nil)
        return image;

    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    // Seashell color                                                                                                                                                                                                                                                           
    UIColor* color = [UIColor colorWithRed:255/255.0 green:245/255.0 blue:238/255.0 alpha:1.0];
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);

    image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}
Run Code Online (Sandbox Code Playgroud)

K-b*_*llo 9

这是相当的Android代码:

// CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
Rect rect = new Rect(0, 0, 1, 1);

//UIGraphicsBeginImageContext(rect.size);
//CGContextRef context = UIGraphicsGetCurrentContext();
Bitmap image = Bitmap.createBitmap(rect.width(), rect.height(), Config.ARGB_8888);
Canvas canvas = new Canvas(image);

//UIColor* color = [UIColor colorWithRed:255/255.0 green:245/255.0 blue:238/255.0 alpha:1.0];
int color = Color.argb(255, 255, 245, 238);

//CGContextSetFillColorWithColor(context, [color CGColor]);
Paint paint = new Paint();
paint.setColor(color);

//CGContextFillRect(context, rect);
canvas.drawRect(rect, paint);

//image = UIGraphicsGetImageFromCurrentImageContext();
//UIGraphicsEndImageContext();
/** nothing to do here, we already have our image **/
/** and the canvas will be released by the GC     **/
Run Code Online (Sandbox Code Playgroud)

现在,如果你想在XML中这样做更容易:

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <size android:width="1px" android:height="1dp"/>
    <solid android:color="#FFFFF5EE/>
</shape>
Run Code Online (Sandbox Code Playgroud)

虽然那不会给你一个Bitmap,但是一个Drawable.如果你打算把它画到某处,那就没关系了.如果你确实需要a Bitmap,那么你将不得不使用上面的代码来创建一个Canvasa Bitmap并将其绘制Drawable到它中.