Java – Copy the Paint object

Copy the Paint object… here is a solution to the problem.

Copy the Paint object

Well, I’m not sure how to describe this. I made a class called ScreenAreas that defines a specific area on the screen. Later, I’m drawing these ScreenAreas.

What I want to do is couple the Paint properties (Color, strokeWidth, Shaddowsettings, etc.) to these ScreenAreas so that I don’t have to reset all of them when I draw them again.

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

In my main class, I build them using the following method:

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(
            50K 
            50K 
            80, 
            80,
            paint);

I just do this when I try to draw them :

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

However, both areas will be given the same color. In fact, they are given the last color used. This may be because the Paint object in the ScreenArea simply points to the same Paint object in the main class. The question is, how to solve this problem!

Anyone?

Solution

You should remember that the Paint object has one copy constructor :

this.paint = paint;

In your ScreenArea constructor, you can use :

this.paint = new Paint(paint);

Related Problems and Solutions