簡體   English   中英

在android中創建帶有顏色的圖像

[英]create a image with color in android

設置背景似乎並沒有提供關於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;
}

這是等效的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 如果您打算將其繪制在某個地方,那就很好。 如果您確實需要Bitmap ,則必須使用上面的代碼從Bitmap創建Canvas並將其Drawable到其中。

這可以幫助您創建具有特定顏色的位圖圖像。 首先創建一個名稱為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 [] pixel = 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));
 }
}

使用此功能,可以將位圖設置為listview項,以使listitem不會折疊

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM