Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine Canvas and layout (Android)

My question about Android UI. When we work with XML-layout we write (for example)

setContentView(R.layout.main);

And when we work with 2d-graphics we write

Draw2D d = new Draw2D(this);
setContentView(d);

So what if I want to use both? I need to use layout-xml and a part of a screen is fir painting (Canvas). I read about surfaceView, but what about simple using Canvas?

like image 484
user1752669 Avatar asked Oct 31 '12 09:10

user1752669


People also ask

What is onDraw method in Android?

The parameter to onDraw() is a Canvas object that the view can use to draw itself. The Canvas class defines methods for drawing text, lines, bitmaps, and many other graphics primitives. You can use these methods in onDraw() to create your custom user interface (UI).

What is SurfaceView?

A SurfaceView is a custom view in Android that can be used to drawn inside it. The main difference between a View and a SurfaceView is that a View is drawn in the UI Thread , which is used for all the user interaction.

What is matrix in canvas Android?

Matrix. A 3 by 3 Matrix that stores information which can be used to transform a canvas. A Matrix can store the following kind of transformation information: scale, skew, rotation, translation. Below is an example of using a Matrix to transform a Bitmap that is drawn on a Canvas.


1 Answers

You can actually inflate your layout from an XML file and then retrieve any view to draw on it. SurfaceView are especially convenient for drawing.

You can find below an example:

main.xml:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <SurfaceView
        android:id="@+id/surface"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</FrameLayout>

TestActivity.java:

public class TestActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    SurfaceView surface = (SurfaceView) findViewById(R.id.surface);
    surface.getHolder().addCallback(new Callback() {

        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            // Do some drawing when surface is ready
            Canvas canvas = holder.lockCanvas();
            canvas.drawColor(Color.RED);
            holder.unlockCanvasAndPost(canvas);
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        }
    });
}
}
like image 90
sdabet Avatar answered Sep 28 '22 01:09

sdabet