The Android framework API provides 2D drawing APIs for simple animations that do not require significant dynamic changes. There are two implementation methods using this API.
1. Drawing to view 2. Drawing on canvas
1.Select a circle to view
Drawing for viewing is the best option when your user interface does not require dynamic changes in the application. This can be achieved by simply extending the View class and defining the onDraw () callback method.
Use the Canvas provided to you for your entire drawing,
using various methods of Canvas.draw ... () (Example: canvas.drawCircle (x / 2, y / 2, radius, paint);). onDraw () is a callback method that is called when the view is first drawn.
The following is a simple code example for drawing a circle: -
MainActivity.java
public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(new MyView(this)); } public class MyView extends View { public MyView(Context context) { super(context);
2. Drawing a rectangle on canvas
To draw dynamic 2D graphics, where you need to draw yourself regularly in your application, drawing on canvas is the best option. The canvas works for you as an interface, on the actual surface on which your graphics will be drawn.
If you need to create a new canvas, you must define a bitmap on which the actual drawing will be performed. A bitmap is always required for a canvas. The following example explains how to draw a rectangle: -
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/mylayout"> </LinearLayout>
MainActivity.java
public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Paint paint = new Paint(); paint.setColor(Color.parseColor("#DD4N5C")); Bitmap bitmap = Bitmap.createBitmap(512, 800, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); canvas.drawRect(150, 150, 250, 250, paint); LinearLayout layout = (LinearLayout) findViewById(R.id.mylayout); layout.setBackgroundDrawable(new BitmapDrawable(bitmap)); } }