Search code examples
javaandroidair-native-extension

Text to bitmap wrong color


We are building a native extension for air, to generate bitmap data from text.

The code below generates the bitmap of a smiley ant "test" those should bee yellow but the color is blue.

https://i.sstatic.net/wC1ZH.png

After a lot of searching and trying different example code we are stuck.

    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;


}

When logging the returned pixels its already blue so we assume it goes wrong in this function.


Solution

  • It seems that the red and blue color channel are switched.

    Fixed it by reversing the blue and red color chanel:

    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);
    
    }
    

    It is not the best way, but i can't find a better solution