logicalfox
logicalfox

Reputation: 83

Displaying a Bitmap on Canvas in Surfaceview

I am trying to develop an android application to display a zoom-able, pan-able map, (which is just a bitmap image), that also allows the user to click on certain points on the map.

I am struggling to find the most effective way of implementing such an app. After trying numerous other methods, (including Webviews, OpenLayers), the best way, (according to this site at least), seems to be using a SurfaceView with a Canvas. The code I have so far is pieced together from snippets I found all over the internet, so it just crashes. I have included it here anyway in the hope it gives some idea of what I am trying to achieve:

public class Main extends Activity {

private Bitmap bmp; 
    private SurfaceView surfaceView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        surfaceView = (SurfaceView)findViewById(R.id.surface);
        bmp = BitmapFactory.decodeResource(getResources(),
             R.drawable.testmapbmp);
        //decode the bitmap file

        Canvas canvas = new Canvas(bmp);
        //create a canvas from the bitmap, then display it in surfaceview
        surfaceView.draw(canvas);
    }
}

Is this the best way to achieve the functionality I want for my application? Or is there a better way, especially if I could run into problems later on, implementing the clickable sections of the map, for example.

I really need help from someone who has created something like this before, so I can get my train-of-thought on the problem, but I greatly appreciate any help/pointers/tips at all!

Thanks

Upvotes: 2

Views: 7791

Answers (1)

EvilDuck
EvilDuck

Reputation: 4436

Your piece of code is not really correct.

Usualy if you want to do this kind if things you need to create your own custom view (either by inheriting View or SurfaceView). In your View subclass you need to override method onDraw(Canvas) and draw your bitmap on canvas by using one of canvas methods.

To make it pannable and pinch-zoomable you need to use Scroller and ScaleGestureDetector classes. Usually panning or scaling is done by applying affine transformations to a canvas by using it's methods (rotate, scale, translate).

Difference between SurfaceView and View is that in SurfaceView you can draw directly from separate thread, which means you can organize sort of rendering loop there and draw from it. It is good for simple games and animation effects. I believe, for purpose of drawing a bitmap this is overkill and much simpler to subclass View.

I'd start with this and this, if I were you.

Upvotes: 2

Related Questions