Bob
Bob

Reputation: 55

Java: Android: changing color of bitmap on canvas in code

I'm trying to do something that I thought was simple but apparently it's not!

I'm making a simple app to learn Android game dev. At the moment, the user clicks on the screen and a sprite is displayed. The sprite is just a solid white square. I want to change that in the code.

I think I'm spoiled by C#/XNA where, if a sprite is solid white, you can set the colour in the draw method. That doesn't seem to work here, even when I used the paint function. I've done a bit of research but all the solutions don't seem to be quite what I'm looking for, and also very complicated. I'm hoping to find something at least simpler to mess with if I can't find the exact solution. Here's the relevant code so far:

From the view:

    private Sprite createSprite(int resouce) {
    Bitmap bmp = BitmapFactory.decodeResource(getResources(), resouce);
    return new Sprite(this, bmp, touchX, touchY);

the view onDraw method:

        if (touched == true)
    {
        canvas.drawColor(colors[nextColor]);
        lastColor = colors[nextColor];

        //add bitmap to array
        sprites.add(createSprite(R.drawable.test));
        //draw sprites
        for (Sprite sprite : sprites) {
            sprite.onDraw(canvas);
        }

relevant code from the sprite class:

    private Paint paint = new Paint();

public Sprite(DaphnyView daphView, Bitmap bmp, int positionX, int positionY) {
    width = bmp.getWidth();
    height = bmp.getHeight();
    DaphView = daphView;
    Bmp = bmp;
    PositionX = positionX;
    PositionY= positionY;
    paint.setColor(Color.GREEN);
}

public void onDraw(Canvas canvas) {
    canvas.drawBitmap(Bmp, PositionX, PositionY, paint);

}

If anyone can help me out or at least point me to a good starting point, it would be a great help. Thanks!

Upvotes: 0

Views: 1358

Answers (1)

Bob
Bob

Reputation: 55

I found a solution by creating a new canvas to modify the bitmap, then passing this modified bitmap back to the original canvas.

Upvotes: 1

Related Questions