Lumis
Lumis

Reputation: 21629

Prevent drawing beyond canvas with SurfaceView

Is there way to prevent drawing of parts of objects, like bitmaps or paths, which go beyond the borders of Canvas in SurfaceView?

When I gradually scale an object beyond the Canvas' size, especially with blurred paint, it all slows down to a stand still and I have to wait few seconds to get the control back -- it is not responsive. I scale an object by moving my finger over the screen; if I do it too fast and scale it up, then it really slows down drawing.

I did not have the same problem when using just ordinary View canvas, so don't know what is slowing it down. It's as though SurfaceView responds too fast and then gets congested.

So one idea to improve this, is to prevent drawing outside canvas, but not sure if SurfaceView has such clipping options.

Upvotes: 5

Views: 1985

Answers (3)

s.d
s.d

Reputation: 29436

I'm not sure if canvas would actually draw things beyond the dimensions, that wouldn't be a smart thing to do. Still, you can use clipRect() to define a clip region.

Are you applying filters like blur per frame ? that might be pretty expensive.

Also, are you triggering draw calls on touch event ? Touch events are generated very quickly and will flood the rendering thread. You might want to pick up events at a slower rate: https://groups.google.com/forum/?fromgroups=#!topic/android-developers/Oe6k1_bm38o

Upvotes: 1

Andres Lopez
Andres Lopez

Reputation: 161

When you put the SurfaceView on the layout of your activity, you can use the padding attributes like:

android:paddingLeft="20dp"
android:paddingTop="20dp"
android:paddingRight="20dp"
android:paddingBottom="20dp"

It works like this:

Padding depiction

To draw your canvas you can draw dinamically the borders with:

canvas.drawLine(1,1,canvas.getWidth()-1,1);  //Top border
canvas.drawLine(1,1,1,canvas.getHeight()-1);  //Left border
canvas.drawLine(1,canvas.getHeight()-1,canvas.getWidth()-1,canvas.getHeight()-1);  //Bottom border
canvas.drawLine(canvas.getWidth()-1,1,canvas.getWidth()-1,canvas.getHeight()-1);  //Right border

Upvotes: 0

Trevor
Trevor

Reputation: 10993

One solution perhaps is by using one of the Canvas .drawBitmap methods that accepts a source Rect / RectF argument, so that only the visible portion of the Bitmap is rendered. I've just done this on my own project to speed up SurfaceView performance where I have several Bitmaps that are sometimes only partially in view.

Upvotes: 1

Related Questions