gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:39:55 25 4
gpt4 key购买 nike

设置背景似乎没有给出任何关于 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 放入其中。

关于android - 在android中创建一个有颜色的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14035498/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com