Practical 10 : Android draw shapes using canvas - IndianTechnoEra
Latest update Android YouTube

Practical 10 : Android draw shapes using canvas

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);
    }
}
```

Code:

Output:

Practical 10 : Android draw shapes using canvas


Post a Comment

Feel free to ask your query...
Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.