Aim:
Aim: Write a program to draw circles, rectangles, and other shapes using `Canvas`.
The Canvas class provides a powerful set of drawing tools for creating custom graphics in an Android app.
It is usually used to draw 2D graphics, such as lines, rectangles, circles, and text on a View or SurfaceView.
Process:
1. Create a new Android Studio project.2. In the `activity_main.xml` file, add a `View` element with a custom `MyCanvas` class as its `android:class` attribute value.
3. In the `MyCanvas` class, override the `onDraw()` method and use the `Canvas` class to draw shapes using methods such as `drawCircle()`, `drawRect()`, and `drawLine()`.
4. In the `MainActivity` class, set the content view to the `activity_main.xml` layout.
5. Run the app to see the shapes drawn on the screen.
Code Step:
1. In the `activity_main.xml` file, add the following code to define a `MyCanvas` view:```xml
<com.example.myapplication.MyCanvas
android:id="@+id/my_canvas"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
2. In the `MyCanvas` class, add the following code to override the `onDraw()` method and draw shapes:
```java
public class MyCanvas extends View {
public MyCanvas(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Draw a circle
Paint paint = new Paint();
paint.setColor(Color.BLUE);
canvas.drawCircle(100, 100, 50, paint);
// Draw a rectangle
paint.setColor(Color.RED);
canvas.drawRect(200, 200, 300, 300, paint);
// Draw a line
paint.setColor(Color.GREEN);
canvas.drawLine(0, 0, getWidth(), getHeight(), paint);
}
}
```
3. In the `MainActivity` class, add the following code to set the content view to the `activity_main.xml` layout:
```java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
```
