Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy Paint object

Okay, I am not sure how to describe this. I have made a Class called ScreenAreas that defines specific areas on the screen. Later on, I am drawing these ScreenAreas.

What I would like to do, is to couple Paint attributes (Color, strokeWidth, Shaddowsettings, etc) to these ScreenAreas, in such a way, that I don't have to reset all these attributes, when drawing them again.

This is my ScreenArea Class: import android.graphics.Canvas; import android.graphics.Paint;

public class ScreenArea {

private int xMin;
private int yMin;
private int xMax;
private int yMax;
private Paint paint;

public ScreenArea(int x1, int x2, int y1, int y2, Paint paint) {
    this.setXMin(x1);
    this.setXMax(x2);
    this.setYMin(y1);
    this.setYMax(y2);
    this.paint = paint;

}

// I removed the getters and setters for clarity

public void draw(Canvas canvas){
    canvas.drawRect(this.xMin, this.yMin, this.xMax, this.yMax, this.paint);
}
}

And in my main Class I am constructing them using:

paint.setColor(Color.rgb(10,10,10));
area1 = new ScreenArea (
            0,
            0,
            100,
            100,
            paint);

paint.setColor(Color.rgb(100,100,100));
area2 = new ScreenArea(
            20, 
            20, 
            80, 
            80,
            paint);

When I try to draw them, I simply do:

area1.draw(canvas);
area2.draw(canvas);

Both of the area's will be given the same color, though. In fact they are given the last color used. Probably, this is because the Paint objects in the ScreenArea are simply pointing to the same Paint object in the main Class. The question is, how to solve this problem!

Anyone?

like image 924
MWB Avatar asked Dec 03 '22 16:12

MWB


2 Answers

You should remember that Paint object has a copy constructor. So instead of:

this.paint = paint;

within your ScreenArea constructor, you can use:

this.paint = new Paint(paint);
like image 173
Bartek Lipinski Avatar answered Dec 14 '22 14:12

Bartek Lipinski


The answer is good, but if for some reason you don't want to instantiate a new Paint (perhaps because you're inside onDraw(), which I realize is not the case here) then you can use Paint.set().

public void set (Paint src) Added in API level 1

Copy the fields from src into this paint. This is equivalent to calling get() on all of the src fields, and calling the corresponding set() methods on this.

Replace private Paint paint; with private Paint paint = new Paint(); and then this.paint = paint; (which just copies to pointer to the Paint object) with this.paint.set(paint); (which copies the fields from paint to this.paint.

like image 27
Mark Cramer Avatar answered Dec 14 '22 12:12

Mark Cramer