我们正在构建一个 Air 原生扩展,以从文本生成位图数据。
下面的代码生成笑脸 Ant 的位图“测试”那些应该是黄色但颜色是蓝色的。
经过大量搜索并尝试不同的示例代码后,我们陷入了困境。
public static Bitmap drawText(String text, int textWidth, int textSize, String color) {
try {
text = URLDecoder.decode("%F0%9F%98%8D test", "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// Get text dimensions
TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.LINEAR_TEXT_FLAG);
textPaint.setColor(Color.parseColor("#ffe400"));
textPaint.setTextSize(textSize);
textPaint.setAntiAlias(true);
StaticLayout mTextLayout = new StaticLayout(text, textPaint, textWidth, Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
// Create bitmap and canvas to draw to
Bitmap b = Bitmap.createBitmap(textWidth, mTextLayout.getHeight(), Config.ARGB_8888);
Canvas c = new Canvas(b);
// Draw text
c.save();
c.translate(0, 0);
mTextLayout.draw(c);
c.restore();
Extension.log("Color " + Integer.toString(b.getPixel(15,10), 16));
return b;
}
当记录返回的像素时,它已经是蓝色的,所以我们假设这个函数出了问题。
最佳答案
看来红色和蓝色 channel 被切换了。
通过颠倒蓝色和红色 channel 修复了这个问题:
private static Bitmap reversColors(Bitmap b){
int width = b.getWidth();
int height = b.getHeight();
int[] pixels = new int[width * height];
b.getPixels(pixels, 0, width, 0, 0, width, height);
int[] finalArray = new int[width * height];
for(int i = 0; i < finalArray.length; i++) {
int red = Color.red(pixels[i]);
int green = Color.green(pixels[i]);
int blue = Color.blue(pixels[i]);
int alpha = Color.alpha(pixels[i]);
finalArray[i] = Color.argb(alpha, blue, green, red);
}
return Bitmap.createBitmap(finalArray, width, height, Bitmap.Config.ARGB_8888);
}
这不是最好的方法,但我找不到更好的解决方案
关于java - 文本到位图颜色错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30024551/