Mark Jacobsen
Mark Jacobsen

Reputation: 351

Displaying only certain part of image on a Canvas

I am currently drawing an image on a canvas in Android Studio like so:

public class Floor{
    int x;
    int y;
    int width;
    int height;
    Drawable image;

    public Floor(int x, int y, int width, int height, Context context) {
        this.x = x;
        this.y = y;
        this.height = height;
        this.width = width;
        this.image = this.context.getResources().getDrawable(R.drawable.floorimage);
    }

    // this method is called in the draw loop
    public void draw(Canvas canvas) {

        Rect imageBounds = new Rect(this.x, this.y, this.x + this.width, this.y + this.height);

        this.image.setBounds(imageBounds);
        this.image.draw(canvas);
    }
}

So the image size is set according to the width and height. I however don't want to reset the image size, I want to draw the part of the image, that is included in the width and height.

To vizualize:

I want to only draw the separated part of the image but still other objects outside the separated part

I am aware of this thread: Android - Display part of a large image

However that thread only shows how to solve my problem for an ImageView. Does anyone have a solution for doing this in a canvas?

Upvotes: 2

Views: 1074

Answers (1)

Osagui Aghedo
Osagui Aghedo

Reputation: 350

Try this in Floor.draw() :

public void draw(Canvas canvas) {

 Rect canvasBounds = canvas.getClipBounds();         //get the current clip(Canvas drawing area)
 this.image.setBounds(canvasBounds);      //same bounds as canvas, so image is the same size. We clip next

 Rect imageBounds=new Rect(0,0,this.width,this.height); //You should move this line to constructor. You know, performance and all.                                                                

 canvas.save();                 //save the current clip. You can't use canvasBounds to restore it later, there is no setClipBounds()
 canvas.clipRect(imageBounds); //clip the canvas so you draw only the width and height u want
 this.image.draw(canvas);
 canvas.restore();       //restore the Canvas clip. 

 //do other drawings with full size canvas

}

Happy coding!

Upvotes: 1

Related Questions