4

设置背景似乎没有给出任何关于 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;
}
4

2 回答 2

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     **/

现在,如果您想在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>

虽然那不会给你一个Bitmap,而是一个Drawable。如果你打算把它画在某个地方,那很好。如果您确实需要 a Bitmap,那么您将不得不使用上面的代码Canvas从 a创建 aBitmap并将您的画Drawable入其中。

于 2012-12-26T03:36:58.660 回答
-3

这有助于您创建具有特定颜色的位图图像。首先创建一个名为 sampleBitmap 的位图,如下所示

Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types
Bitmap sampleBitmap = Bitmap.createBitmap(300, 300, conf); // this creates a MUTABLE bitmap

接下来使用以下代码获取创建的位图的每个像素

// int[] 像素 = new int[sampleBitmap.getHeight()*sampleBitmap.getWidth()];

for (int i=0; i < sampleBitmap.getWidth(); i++)
{
for (int j=0; j < sampleBitmap.getHeight(); i++)
 {
    sampleBitmap.setPixel(i, j, Color.rgb(someColor1, someColor2, someColor3));
 }
}

使用它,您可以将位图设置为列表视图项,以便列表项不会折叠

于 2012-12-26T03:31:49.723 回答