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?
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).
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.
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.
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) {
}
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With