Reader small image

You're reading from  Android Programming with Kotlin for Beginners

Product typeBook
Published inApr 2019
Reading LevelIntermediate
PublisherPackt
ISBN-139781789615401
Edition1st Edition
Languages
Right arrow
Author (1)
John Horton
John Horton
author image
John Horton

John Horton is a programming and gaming enthusiast based in the UK. He has a passion for writing apps, games, books, and blog articles. He is the founder of Game Code School.
Read more about John Horton

Right arrow

Chapter 20. Drawing Graphics

This entire chapter will be about the Android Canvas class and some related classes, such as Paint, Color, and Bitmap. When combined, these classes bring great power when it comes to drawing on the screen. Sometimes, the default UI provided by the Android API isn't what we need. If we want to make a drawing app, draw graphs, or perhaps make a game, we need to take control of every pixel that the Android device has to offer.

In this chapter, we will cover the following topics:

  • Gain an understanding of the Canvas class and some related classes

  • Write a Canvas-based demo app

  • Look at the Android coordinate system so that we know where to do our drawing

  • Learn about drawing and manipulating bitmap graphics

  • Write a bitmap graphics-based demo app

So, let's get drawing!

Understanding the Canvas class


The Canvas class is part of the android.graphics package. In the next two chapters, we will be using all the following import statements from the android.graphics package and one more from the now familiar View package. They give us access to some powerful drawing functions from the Android API:

import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.widget.ImageView

First, let's talk about Bitmap, Canvas, and ImageView, as highlighted in the previous code.

Getting started drawing with Bitmap, Canvas, and ImageView

As Android is designed to run all types of mobile apps, we can't immediately start typing our drawing code and expect it to work. We need to do a bit of preparation (that is, more coding) to consider the specific device that our app is running on. It is true that some of this preparation can be slightly counterintuitive, but we will go through this one step at a time.

Canvas...

Using the Canvas class


Let's take a look at the code and the different stages that are required to get drawing, then we can quickly move on to drawing something, for real, with the Canvas demo app.

Preparing the instances of the required classes

The first step is to turn the classes that we need into usable instances.

First, we declare all the instances that we require. We can't initialize the instances right away, but we can make sure that we initialize them before they are used, so we use lateinit in the same way we did in the Animation demo app:

// Here are all the objects(instances)
// of classes that we need to do some drawing
lateinit var myImageView: ImageView
lateinit var myBlankBitmap: Bitmap
lateinit var myCanvas: Canvas
lateinit var myPaint: Paint

The previous code declares references of the ImageView, Bitmap, Canvas, and Paint types. They are named myImageView, myBlankBitmap, myCanvas, and myPaint, respectively.

Initializing the objects

Next, we need to initialize our new objects before...

The Canvas Demo app


First, create a new project to explore the topic of drawing with Canvas. We will reuse what we have learned and, this time, we will also draw to the Bitmap instance.

Creating a new project

Create a new project and call it Canvas Demo, and make sure that you choose the Empty Activity template option.

In this app, we will make a change that we have not seen before. We will be using the vanilla version of the Activity class. Therefore, MainActivity will inherit from Activity instead of AppCompatActivity, as has been the case previously. We are doing this because we are not using a layout from an XML file, and so we have no need for the backward compatibility features of AppCompatActivity as we did in all the previous projects.

You should edit the class declaration as follows.

class MainActivity : Activity() {

You will also need to add the following import statement:

import android.app.Activity

Note

The complete code for this app can be found in the download bundle in the Chapter20...

The Android coordinate system


As you will see, drawing a bitmap graphic is trivial. However, the coordinate system that we use to draw our graphics on requires a brief explanation.

Plotting and drawing

When we draw a bitmap graphic on the screen, we pass in the coordinates that we want to draw the object to. The available coordinates of a given Android device depend upon the resolution of its screen.

For example, the Google Pixel phone has a screen resolution of 1,920 pixels (across) by 1,080 pixels (down) when held in landscape orientation.

The numbering system of these coordinates starts in the top left-hand corner at 0,0, and proceeds downward and to the right until the bottom-right corner is pixel 1919, 1079. The apparent 1-pixel disparity between 1,920/1,919 and 1,080/1,079 is because the numbering starts at 0.

So, when we draw a bitmap graphic or anything else on the screen (such as Canvas circles and rectangles), we must specify an x, y coordinate.

Furthermore, a bitmap graphic (or Canvas...

Creating bitmap graphics with the Bitmap class


Let's examine a bit of theory before we dive into the code and consider exactly how we are going to draw images to the screen. To draw a bitmap graphic, we will use the drawBitmap function of the Canvas class.

First, we will need to add a bitmap graphic to the project in the res/drawable folder – we will do this in reality in the Bitmap demo app later. For now, assume that the graphics file/bitmap has a name of myImage.png.

Next, we will declare an object of the Bitmap type in the same way that we did for the Bitmap object that we used for our background in the previous demo.

Next, we will need to initialize the myBitmap instance using our preferred image file, which we previously added to the project's drawable folder:

myBitmap = BitmapFactory.decodeResource
                (resources, R.drawable.myImage)

The decodeResource function of the BitmapFactory class is used to initialize myBitmap. It takes two parameters; the first is the resources property...

Manipulating bitmaps


Quite often, however, we need to draw bitmaps in a rotated or otherwise altered state. It is quite easy to use Photoshop, or whatever your favorite image editing software happens to be and create more bitmaps from the original bitmap to face other directions. Then, when we come to draw our bitmap, we can simply decide which way and draw the appropriate pre-loaded bitmap.

However, I think it will be much more interesting and instructive if we work with just the one single source image and learn about the class that Android provides to manipulate images with our Kotlin code. You will then be able to add rotating and inverting graphics to your app developer's toolkit.

What is a bitmap?

A bitmap is called a bitmap because that is exactly what it is: a map of bits. While there are many bitmap formats that use different ranges and values to represent colors and transparency, they all amount to the same thing. They are a grid or map of values and each value represents the color...

The Bitmap manipulation demo app


Now that we have studied the theory, let's draw and spin some bitmaps. First, create a new project and call it Bitmap manipulation. Choose the Empty Activity option with all the other settings as they have been throughout the book.

Adding the Bob graphic to the project

Right-click and select Copy to copy the bob.png graphics file from the download bundle in the Chapter20/Bitmap Manipulation/drawable folder. Bob, represented by bob.png, is a simple, static video game character.

In Android Studio, locate the app/res/drawable folder in the project explorer window and paste the bob.png image file into it. The following screenshot makes it clear where this folder is located and what it will look like with the bob.png image in it:

Right-click on the drawable folder and select Paste to add the bob.png file to the project. Click on OK twice to confirm the default options for importing the file into the project.

In this app, we will make the same change that we did in...

Frequently asked question


Q 1) I know how to do all this drawing, but why can't I see anything move?

A) To see things move, you need to be able to regulate when each part of the drawing occurs. You need to use animation techniques. This is not trivial, but it is not beyond the grasp of a determined beginner, either. We will study the required topics in the next chapter.

Summary


In this chapter, we saw how to draw custom shapes, text, and bitmaps. Now that we know how to draw and manipulate both primitive shapes, text, and bitmaps, we can take things up a level.

In the next chapter, we will start our next multi-chapter app, which is a kid's-style drawing app that comes to life at the tap of a button.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Android Programming with Kotlin for Beginners
Published in: Apr 2019Publisher: PacktISBN-13: 9781789615401
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at ₹800/month. Cancel anytime

Author (1)

author image
John Horton

John Horton is a programming and gaming enthusiast based in the UK. He has a passion for writing apps, games, books, and blog articles. He is the founder of Game Code School.
Read more about John Horton