DEV Community

Maria Luíza
Maria Luíza

Posted on

Canvas in Jetpack Compose

Android gif

Hello, fantastic person on the internet! I hope you’re doing well.

We all know that Jetpack Compose is excellent for creating native Android UI, but do you know how we can achieve this using the Canva API?

 

Canvas API

The Canvas API unveils a new realm of possibilities, allowing us to paint and sculpt the UI with unparalleled precision and artistry.

 

Screen

We need first to understand how the screen works. Our interface is composed of many pixels, and the more pixels we have, the cleaner the components will be.

To observe that, we can simply zoom in on a component:

pixel image

Knowing that we can begin drawing using the Canva API.

 

Implementation

Go to your compose function and invoke the Canvas method.

Now, you have the ability to start drawing. These are some simple functions that can assist you:

  • Use drawRect() to draw a square.
  • Use drawCircle() to draw a circle.
  • Use drawRoundRect() to draw a square with rounded corners.

 

Square

To draw a simple square:

square image

To draw a square with rounded corners:

square with rounded corners

 

Circle

To draw a simple circle:

circle image

To draw a simple circle with stroke line:

circle with stroke line image

 

Positions

You can also change the position of the element by a specified number of pixels.

Imagine that I have a square of 100 pixels:

pixel image

I want to draw a square in the bottom left corner, taking up only half of the layout. We can use topLeft to set the alignment, and I can adjust the offset for both the X and Y axes to 100f:

Your layout is going to look like this:

pixel image

 

The power of Canvas

You may be wondering why you need to draw a circle or a square. The answer to that question is that, with simple symbols like that, you can design many other beautiful and unthinkable illustrations.

For example:

Amazing graphics

graphics

Logos

instagram logo

Or any shapes

spiral, flower and waves images

 

Conclusion

The Canvas API can be extremely useful when you need to create unique illustrations or when you can’t find a high-quality one.

You can combine the Canvas API with Compose animations to create beautiful layouts. Check my article on animation created using Compose for more information on this topic.

All the code and examples it is in this repository.

Happy coding ❤


Please let me know what you think in the comments…

Connect with me 👇

Linkedin

GitHub

Instagram

Twitter

Medium

dinossor google gif

Top comments (0)