Invert bitmap colors

前端 未结 4 1274
悲&欢浪女
悲&欢浪女 2021-02-06 11:10

I have the following problem. I have a charting program, and it\'s design is black, but the charts (that I get from the server as images) are light (it actually uses only 5 colo

4条回答
  •  既然无缘
    2021-02-06 12:13

    A quick way would be to use AvoidXfermode to repaint just those colors you want changed - you could then switch between any colors you want. You just need to do something like this:

    // will change red to green
    Paint change1 = new Paint();
    change1.setColor(Color.GREEN);
    change1.setXfermode(new AvoidXfermode(Color.RED, 245, AvoidXfermode.Mode.TARGET));
    
    Canvas c = new Canvas();
    c.setBitmap(chart);
    c.drawRect(0, 0, width, height, change1);
    
    // rinse, repeat for other colors
    

    You may need to play with the tolerance for the AvoidXfermode, but that should do what you want a lot faster than a per-pixel calculation. Also, make sure your chart image is in ARGB8888 mode. By default, Android tends to work with images in RGB565 mode, which tends to mess up color calculations like you want to use - to be sure, you can make sure your image is both in ARGB8888 mode and mutable by calling Bitmap chart = chartFromServer.copy(Config.ARGB_8888, true); before you setup the Xfermode.

    Clarification: to change other colors, you wouldn't have to re-load the images all over again, you would just have to create other Paints with the appropriate colors you want changed like so:

    // changes green to red
    Paint change1 = new Paint();
    change1.setColor(Color.GREEN);
    change1.setXfermode(new AvoidXfermode(Color.RED, 245, AvoidXfermode.Mode.TARGET));
    
    // changes white to blue
    Paint change2 = new Paint();
    change2.setColor(Color.BLUE);
    change2.setXfermode(new AvoidXfermode(Color.WHITE, 245, AvoidXfermode.Mode.TARGET));
    
    // ... other Paints with other changes you want to apply to this image
    
    Canvas c = new Canvas();
    c.setBitmap(chart);
    c.drawRect(0, 0, width, height, change1);
    c.drawRect(0, 0, width, height, change2);
    //...
    c.drawRect(0, 0, width, height, changeN);
    

提交回复
热议问题