27
Android Graphics MCA 5th 650003 Mr. Pritesh N. Patel ISTAR Page 1 Android Drawing and Animations Android graphics are powered by a custom 2D graphics library, and the framework provides support for high performance 3D graphics in the form of OpenGL ES and RenderScript. Consider your Options When drawing 2D graphics, you'll typically do so in one of two ways: A. Draw your graphics or animations into a View object from your layout. In this manner, the drawing (and any animation) of your graphics is handled by the system's normal View hierarchy drawing process you simply define the graphics to go inside the View. B. Draw your graphics directly to a Canvas. This way, you personally call the appropriate class's draw() method (passing it your Canvas), or one of the Canvas draw...() methods (like drawPicture() ). In doing so, you are also in control of any animation. Option "A," drawing to a View, is your best choice when you want to draw simple graphics that do not need to change dynamically and are not part of a performance-intensive game. For example, you should draw your graphics into a View when you want to display a static graphic or predefined animation, within an otherwise static application. Option "B," drawing to a Canvas, is better when your application needs to regularly re-draw itself. Basically, any video game should be drawing to the Canvas on its own. However, there's more than one way to do this: In the same thread as your UI Activity, wherein you create a custom View component in your layout, call invalidate() and then handle the onDraw() callback.. Or, in a separate thread, wherein you manage a SurfaceView and perform draws to the Canvas as fast as your thread is capable (you do not need to request invalidate() Simple Graphics inside a View If you'll be drawing some simple graphics (images, shapes, colors, pre-defined animations, etc.), then you should probably just draw to the background of a View or to the content of an ImageView in your layout.

Android graphics mca 5th

Embed Size (px)

Citation preview

Page 1: Android graphics mca 5th

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 1

Android Drawing and Animations

Android graphics are powered by a custom 2D graphics library and the

framework provides support for high performance 3D graphics in the form of

OpenGL ES and RenderScript

Consider your Options

When drawing 2D graphics youll typically do so in one of two ways

A Draw your graphics or animations into a View object from your layout In this

manner the drawing (and any animation) of your graphics is handled by the

systems normal View hierarchy drawing process mdash you simply define the

graphics to go inside the View

B Draw your graphics directly to a Canvas This way you personally call the

appropriate classs draw() method (passing it your Canvas) or one of the

Canvas draw() methods (like drawPicture()) In doing so you are also in

control of any animation

Option A drawing to a View is your best choice when you want to draw

simple graphics that do not need to change dynamically and are not part of a

performance-intensive game For example you should draw your graphics into

a View when you want to display a static graphic or predefined animation

within an otherwise static application

Option B drawing to a Canvas is better when your application needs to

regularly re-draw itself Basically any video game should be drawing to the

Canvas on its own However theres more than one way to do this

In the same thread as your UI Activity wherein you create a custom View

component in your layout call invalidate()and then handle

the onDraw() callback

Or in a separate thread wherein you manage a SurfaceView and perform

draws to the Canvas as fast as your thread is capable (you do not need to

request invalidate()

Simple Graphics inside a View

If youll be drawing some simple graphics (images shapes colors pre-defined

animations etc) then you should probably just draw to the background of a View

or to the content of an ImageView in your layout

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 2

Draw with a Canvas

When youre writing an application in which you would like to perform specialized

drawing andor control the animation of graphics you should do so by drawing

through a Canvas A Canvas works for you as a pretense or interface to the

actual surface upon which your graphics will be drawn mdash it holds all of your

draw calls Via the Canvas your drawing is actually performed upon an

underlying Bitmap which is placed into the window

In the event that youre drawing within the onDraw() callback method the Canvas

is provided for you and you need only place your drawing calls upon it You can

also acquire a Canvas from SurfaceHolderlockCanvas() when dealing with a

SurfaceView object (Both of these scenarios are discussed in the following

sections) However if you need to create a new Canvas then you must define

the Bitmap upon which drawing will actually be performed The Bitmap is always

required for a Canvas You can set up a new Canvas like this

Bitmap b = BitmapcreateBitmap(100 100 BitmapConfigARGB_8888)

Canvas c = new Canvas(b)

Now your Canvas will draw onto the defined Bitmap After drawing upon it with

the Canvas you can then carry your Bitmap to another Canvas with one of

the CanvasdrawBitmap(Bitmap) methods Its recommended that you

ultimately draw your final graphics through a Canvas offered to you

by ViewonDraw() or SurfaceHolderlockCanvas() (see the following sections)

The Canvas class has its own set of drawing methods that you can use

like drawBitmap() drawRect()drawText() and many more Other classes

that you might use also have draw() methods For example youll probably have

some Drawable objects that you want to put on the Canvas Drawable has its

own draw() method that takes your Canvas as an argument

Draw On a View

If your application does not require a significant amount of processing or frame-

rate speed (perhaps for a chess game a snake game or another slowly-animated

application) then you should consider creating a custom View component and

drawing with a Canvas in ViewonDraw() The most convenient aspect of doing so

is that the Android framework will provide you with a pre-defined Canvas to which

you will place your drawing calls

To start extend the View class (or descendant thereof) and define

the onDraw() callback method This method will be called by the Android

framework to request that your View draw itself This is where you will perform all

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 3

your calls to draw through the Canvas which is passed to you through

the onDraw() callback

The Android framework will only call onDraw() as necessary Each time that your

application is prepared to be drawn you must request your View be invalidated by

calling invalidate() This indicates that youd like your View to be drawn and

Android will then call your onDraw() method (though is not guaranteed that the

callback will be instantaneous)

Inside your View components onDraw() use the Canvas given to you for all your

drawing using various Canvasdraw() methods or other class draw() methods

that take your Canvas as an argument Once your onDraw() is complete the

Android framework will use your Canvas to draw a Bitmap handled by the system

Note In order to request an invalidate from a thread other than your main

Activitys thread you must call postInvalidate()

Draw On a SurfaceView

The SurfaceView is a special subclass of View that offers a dedicated drawing surface within the View hierarchy The aim is to offer this drawing surface to an applications secondary thread so that the application isnt required to wait until

the systems View hierarchy is ready to draw Instead a secondary thread that has reference to a SurfaceView can draw to its own Canvas at its own pace

To begin you need to create a new class that extends SurfaceView The class

should also implement SurfaceHolderCallback This subclass is an interface that will notify you with information about the underlying Surface such as when it is created changed or destroyed These events are important so that you know

when you can start drawing whether you need to make adjustments based on new surface properties and when to stop drawing and potentially kill some tasks

Inside your SurfaceView class is also a good place to define your secondary Thread class which will perform all the drawing procedures to your Canvas

Instead of handling the Surface object directly you should handle it via a SurfaceHolder So when your SurfaceView is initialized get the SurfaceHolder by

calling getHolder() You should then notify the SurfaceHolder that youd like to receive SurfaceHolder callbacks (from SurfaceHolderCallback) by calling

addCallback() (pass it this) Then override each of the SurfaceHolderCallback methods inside your SurfaceView class

In order to draw to the Surface Canvas from within your second thread you must pass the thread your SurfaceHandler and retrieve the Canvas with lockCanvas()

You can now take the Canvas given to you by the SurfaceHolder and do your necessary drawing upon it Once youre done drawing with the Canvas call

unlockCanvasAndPost() passing it your Canvas object The Surface will now draw

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 4

the Canvas as you left it Perform this sequence of locking and unlocking the canvas each time you want to redraw

Note On each pass you retrieve the Canvas from the SurfaceHolder the previous state of the Canvas will be retained In order to properly animate your graphics

you must re-paint the entire surface For example you can clear the previous state of the Canvas by filling in a color with drawColor() or setting a background image with drawBitmap() Otherwise you will see traces of the drawings you

previously performed

2D Graphics

Android offers a custom 2D graphics library for drawing and animating shapes

and images Theandroidgraphicsdrawable andandroidviewanimation packages

are where youll find the common classes used for drawing and animating in two-

dimensions

This document offers an introduction to drawing graphics in your Android

application Well discuss the basics of using Drawable objects to draw graphics

how to use a couple subclasses of the Drawable class and how to create

animations that either tween (move stretch rotate) a single graphic or animate a

series of graphics (like a roll of film)

Drawables

A Drawable is a general abstraction for something that can be drawn Youll

discover that the Drawable class extends to define a variety of specific kinds of

drawable graphics

including BitmapDrawable ShapeDrawable PictureDrawableLayerDrawable and

several more Of course you can also extend these to define your own custom

Drawable objects that behave in unique ways

There are three ways to define and instantiate a Drawable using an image saved

in your project resources using an XML file that defines the Drawable properties

or using the normal class constructors Below well discuss each the first two

techniques (using constructors is nothing new for an experienced developer)

Creating from resource images

A simple way to add graphics to your application is by referencing an image file

from your project resources Supported file types are PNG (preferred) JPG

(acceptable) and GIF (discouraged) This technique would obviously be preferred

for application icons logos or other graphics such as those used in a game

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 5

To use an image resource just add your file to the resdrawable directory of your

project From there you can reference it from your code or your XML layout

Either way it is referred using a resource ID which is the file name without the

file type extension (Eg my_imagepng is referenced as my_image)

Example code

The following code snippet demonstrates how to build an ImageView that uses an

image from drawable resources and add it to the layout

LinearLayout mLinearLayout

protected void onCreate(Bundle savedInstanceState)

superonCreate(savedInstanceState) Create a LinearLayout in which to add the ImageView

mLinearLayout = new LinearLayout(this) Instantiate an ImageView and define its properties

ImageView i = new ImageView(this) isetImageResource(Rdrawablemy_image)

isetAdjustViewBounds(true) set the ImageView bounds to match the Drawables dimensions isetLayoutParams(new

GalleryLayoutParams(LayoutParamsWRAP_CONTENT LayoutParamsWRAP_CONTENT))

Add the ImageView to the layout and set the layout as the content view mLinearLayoutaddView(i)

setContentView(mLinearLayout)

In other cases you may want to handle your image resource as a Drawable object

To do so create a Drawable from the resource like so

Resources res = mContextgetResources()

Drawable myImage = resgetDrawable(Rdrawablemy_image)

Example XML

The XML snippet below shows how to add a resource Drawable to an ImageView in

the XML layout (with some red tint just for fun)

ltImageView androidlayout_width=wrap_content

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 6

androidlayout_height=wrap_content androidtint=55ff0000

androidsrc=drawablemy_imagegt

Creating from resource XML

By now you should be familiar with Androids principles of developing a User

Interface Hence you understand the power and flexibility inherent in defining

objects in XML This philosophy caries over from Views to Drawables If there is a

Drawable object that youd like to create which is not initially dependent on

variables defined by your application code or user interaction then defining the

Drawable in XML is a good option Even if you expect your Drawable to change its

properties during the users experience with your application you should consider

defining the object in XML as you can always modify properties once it is

instantiated

Once youve defined your Drawable in XML save the file in

the resdrawable directory of your project Then retrieve and instantiate the

object by calling ResourcesgetDrawable() passing it the resource ID of your XML

file (See the example below)

Any Drawable subclass that supports the inflate() method can be defined in XML

and instantiated by your application Each Drawable that supports XML inflation

utilizes specific XML attributes that help define the object properties (see the class

reference to see what these are) See the class documentation for each Drawable

subclass for information on how to define it in XML

Example

Heres some XML that defines a TransitionDrawable

lttransition xmlnsandroid=httpschemasandroidcomapkresandroidgt ltitem androiddrawable=drawableimage_expandgt ltitem androiddrawable=drawableimage_collapsegt

lttransitiongt

With this XML saved in the file resdrawableexpand_collapsexml the following

code will instantiate the TransitionDrawable and set it as the content of an

ImageView

Resources res = mContextgetResources() TransitionDrawable transition = (TransitionDrawable)

resgetDrawable(Rdrawableexpand_collapse)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 7

ImageView image = (ImageView) findViewById(Ridtoggle_image)

imagesetImageDrawable(transition)

Then this transition can be run forward (for 1 second) with

transitionstartTransition(1000)

Canvas class

The Canvas class holds the draw calls To draw something you need 4 basic

components A Bitmap to hold the pixels a Canvas to host the draw calls (writing

into the bitmap) a drawing primitive (eg Rect Path text Bitmap) and a paint (to

describe the colors and styles for the drawing)

Public Constructors

Canvas() Construct an empty raster canvas

Canvas(Bitmap bitmap) Construct a canvas with the specified bitmap to draw into

Public Methods

void drawArc(RectF oval float startAngle float sweepAngle boolean useCenter Paint paint)

Draw the specified arc which will be scaled to fit inside the specified

oval

void drawBitmap(Bitmap bitmap float left float top Paint paint) Draw the specified bitmap with its topleft corner at (xy) using the

specified paint transformed by the current matrix

void drawCircle(float cx float cy float radius Paint paint) Draw the specified circle using the specified paint

void drawColor(int color) Fill the entire canvas bitmap (restricted to the current clip) with the specified color using srcover porterduff mode

void drawLine(float startX float startY float stopX float stopY Paint paint)

Draw a line segment with the specified start and stop xy coordinates using the specified paint

void drawLines(float[] pts Paint paint)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 8

void drawLines(float[] pts int offset int count Paint paint)

Draw a series of lines

void drawOval(RectF oval Paint paint)

Draw the specified oval using the specified paint

void drawPaint(Paint paint)

Fill the entire canvas bitmap (restricted to the current clip) with the specified paint

void drawPicture(Picture picture) Save the canvas state draw the picture and restore the canvas state

void drawPicture(Picture picture Rect dst) Draw the picture stretched to fit into the dst rectangle

void drawPoint(float x float y Paint paint) Helper for drawPoints() for drawing a single point

void drawPoints(float[] pts int offset int count Paint paint) Draw a series of points

void drawPoints(float[] pts Paint paint) Helper for drawPoints() that assumes you want to draw the entire

array

void drawPosText(char[] text int index int count float[] pos Paint paint)

Draw the text in the array with each characters origin specified by the pos array

void drawPosText(String text float[] pos Paint paint) Draw the text in the array with each characters origin specified by the pos array

void drawRGB(int r int g int b) Fill the entire canvas bitmap (restricted to the current clip) with the

specified RGB color using srcover porterduff mode

void drawRect(float left float top float right float bottom Paint paint)

Draw the specified Rect using the specified paint

void drawRect(RectF rect Paint paint)

Draw the specified Rect using the specified paint

void drawRect(Rect r Paint paint)

Draw the specified Rect using the specified Paint

void drawRoundRect(RectF rect float rx float ry Paint paint)

Draw the specified round-rect using the specified paint

void drawText(String text float x float y Paint paint)

Draw the text with origin at (xy) using the specified paint

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 9

void drawText(CharSequence text int start int end float x float

y Paint paint) Draw the specified range of text specified by startend with its origin at (xy) in the specified Paint

void drawText(char[] text int index int count float x float y Paint paint) Draw the text with origin at (xy) using the specified paint

void drawText(String text int start int end float x float y Paint paint) Draw the text with origin at (xy) using the specified paint

void drawTextOnPath(String text Path path float hOffset float vOffset Paint paint)

Draw the text with origin at (xy) using the specified paint along the specified path

void drawTextOnPath(char[] text int index int count Path path float hOffset float vOffset Paint paint)

Draw the text with origin at (xy) using the specified paint along the specified path

int getHeight() Returns the height of the current drawing layer

void getMatrix(Matrix ctm) Return in ctm the current transformation matrix

final Matrix

getMatrix() Return a new matrix with a copy of the canvas current transformation matrix

int getWidth() Returns the width of the current drawing layer

void rotate(float degrees) Preconcat the current matrix with the specified rotation

final void

rotate(float degrees float px float py) Preconcat the current matrix with the specified rotation

void scale(float sx float sy) Preconcat the current matrix with the specified scale

final

void scale(float sx float sy float px float py)

Preconcat the current matrix with the specified scale

void setBitmap(Bitmap bitmap)

Specify a bitmap for the canvas to draw into

void translate(float dx float dy)

Preconcat the current matrix with the specified translation

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 10

Paint class

The Paint class holds the style and color information about how to draw

geometries text and bitmaps

Paint Styles

public static final PaintStyle FILL

Geometry and text drawn with this style will be filled ignoring all stroke-related

settings in the paint

public static final PaintStyle FILL_AND_STROKE

Geometry and text drawn with this style will be both filled and stroked at the same time respecting the stroke-related fields on the paint This mode can give unexpected results if the geometry is oriented counter-clockwise This restriction

does not apply to either FILL or STROKE

public static final PaintStyle STROKE

Geometry and text drawn with this style will be stroked respecting the stroke-related fields on the paint

Public Constructors

Paint()

Create a new paint with default settings

Paint(int flags)

Create a new paint with the specified flags

Paint(Paint paint)

Create a new paint initialized with the attributes in the specified paint parameter

Public Methods

int getAlpha()

Helper to getColor() that just returns the colors alpha value

int getColor()

Return the paints color

ColorFilter getColorFilter()

Get the paints colorfilter (maybe be null)

boolean

getFillPath(Path src Path dst)

Applies anyall effects (patheffect stroking) to src returning

the result in dst

int getFlags()

Return the paints flags

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 11

PaintFontMetrics

getFontMetrics()

Allocates a new FontMetrics object and then calls

getFontMetrics(fm) with it returning the object

int

getFontMetricsInt(PaintFontMetricsInt fmi)

Return the fonts interline spacing given the Paints settings

for typeface textSize etc

float

getFontSpacing()

Return the recommend line spacing based on the current

typeface and text size

MaskFilter getMaskFilter()

Get the paints maskfilter object

Shader getShader()

Get the paints shader object

PaintStyle

getStyle()

Return the paints style used for controlling how primitives

geometries are interpreted (except for drawBitmap which

always assumes FILL_STYLE)

PaintAlign getTextAlign()

Return the paints Align value for drawing text

void

getTextBounds(char[] text int index int count Rect bounds)

Return in bounds (allocated by the caller) the smallest

rectangle that encloses all of the characters with an implied

origin at (00)

void

getTextBounds(String text int start int end Rect bounds)

Return in bounds (allocated by the caller) the smallest

rectangle that encloses all of the characters with an implied

origin at (00)

void

getTextPath(String text int start int end float x float y Path

path)

Return the path (outline) for the specified text

void

getTextPath(char[] text int index int count float x float y

Path path)

Return the path (outline) for the specified text

float getTextScaleX()

Return the paints horizontal scale factor for text

float getTextSize()

Return the paints text size

int getTextWidths(String text float[] widths)

Return the advance widths for the characters in the string

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 12

int

getTextWidths(CharSequence text int start int end float[]

widths)

Return the advance widths for the characters in the string

int getTextWidths(String text int start int end float[] widths)

Return the advance widths for the characters in the string

int getTextWidths(char[] text int index int count float[] widths)

Return the advance widths for the characters in the string

Typeface getTypeface()

Get the paints typeface object

final boolean

isAntiAlias()

Helper for getFlags() returning true if ANTI_ALIAS_FLAG bit is

set AntiAliasing smooths out the edges of what is being

drawn but is has no impact on the interior of the shape

final boolean

isStrikeThruText()

Helper for getFlags() returning true if

STRIKE_THRU_TEXT_FLAG bit is set

final boolean

isSubpixelText()

Helper for getFlags() returning true if SUBPIXEL_TEXT_FLAG

bit is set

final boolean

isUnderlineText()

Helper for getFlags() returning true if

UNDERLINE_TEXT_FLAG bit is set

float measureText(String text)

Return the width of the text

float measureText(CharSequence text int start int end)

Return the width of the text

float measureText(String text int start int end)

Return the width of the text

float measureText(char[] text int index int count)

Return the width of the text

void reset()

Restores the paint to its default settings

void set(Paint src)

Copy the fields from src into this paint

void

setARGB(int a int r int g int b)

Helper to setColor() that takes argb and constructs the

color int

void setAlpha(int a)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 13

Helper to setColor() that only assigns the colors alpha value

leaving its rgb values unchanged

void

setAntiAlias(boolean aa)

Helper for setFlags() setting or clearing the ANTI_ALIAS_FLAG

bit AntiAliasing smooths out the edges of what is being drawn

but is has no impact on the interior of the shape

void setColor(int color)

Set the paints color

ColorFilter setColorFilter(ColorFilter filter)

Set or clear the paints colorfilter returning the parameter

void

setFakeBoldText(boolean fakeBoldText)

Helper for setFlags() setting or clearing the

FAKE_BOLD_TEXT_FLAG bit

void setFlags(int flags)

Set the paints flags

PathEffect setPathEffect(PathEffect effect)

Set or clear the patheffect object

Shader setShader(Shader shader)

Set or clear the shader object

void

setShadowLayer(float radius float dx float dy int color)

This draws a shadow layer below the main layer with the

specified offset and color and blur radius

void

setStrikeThruText(boolean strikeThruText)

Helper for setFlags() setting or clearing the

STRIKE_THRU_TEXT_FLAG bit

void

setStyle(PaintStyle style)

Set the paints style used for controlling how primitives

geometries are interpreted (except for drawBitmap which

always assumes Fill)

void

setSubpixelText(boolean subpixelText)

Helper for setFlags() setting or clearing the

SUBPIXEL_TEXT_FLAG bit

void setTextAlign(PaintAlign align)

Set the paints text alignment

void setTextSize(float textSize)

Set the paints text size

void setTextSkewX(float skewX)

Set the paints horizontal skew factor for text

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 14

Typeface setTypeface(Typeface typeface)

Set or clear the typeface object

void

setUnderlineText(boolean underlineText)

Helper for setFlags() setting or clearing the

UNDERLINE_TEXT_FLAG bit

Types of Gradient

1 Linear Gradient

public LinearGradient (float x0 float y0 float x1 float y1 int[] colors float[]

positions ShaderTileMode tile)

Create a shader that draws a linear gradient along a line

Parameters

x0 The x-coordinate for the start of the gradient line

y0 The y-coordinate for the start of the gradient line

x1 The x-coordinate for the end of the gradient line

y1 The y-coordinate for the end of the gradient line

colors The colors to be distributed along the gradient line

positions

May be null The relative positions [01] of each corresponding color in

the colors array If this is null the the colors are distributed evenly

along the gradient line

tile The Shader tiling mode

2 Sweep Gradient

public SweepGradient (float cx float cy int[] colors float[] positions)

A subclass of Shader that draws a sweep gradient around a center point

Parameters

cx The x-coordinate of the center

cy The y-coordinate of the center

colors The colors to be distributed between around the center There must be

at least 2 colors in the array

positions

May be NULL The relative position of each corresponding color in the

colors array beginning with 0 and ending with 10 If the values are not

monotonic the drawing may produce unexpected results If positions is

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 15

NULL then the colors are automatically spaced evenly

3 Radial Gradient

public RadialGradient (float x float y float radius int[] colors float[] positions

ShaderTileMode tile)

Create a shader that draws a radial gradient given the center and radius

Parameters

x The x-coordinate of the center of the radius

y The y-coordinate of the center of the radius

radius Must be positive The radius of the circle for this gradient

colors The colors to be distributed between the center and edge of the circle

positions

May be NULL The relative position of each corresponding color in the

colors array If this is NULL the the colors are distributed evenly

between the center and edge of the circle

tile The Shader tiling mode

Shader Class

Shader is the based class for objects that return horizontal spans of colors during

drawing A subclass of Shader is installed in a Paint calling

paintsetShader(shader) After that any object (other than a bitmap) that is drawn

with that paint will get its color(s) from the shader

ShaderTileMode CLAMP replicate the edge color if the shader draws

outside of its original bounds

ShaderTileMode MIRROR repeat the shaders image horizontally and

vertically alternating mirror images so that adjacent images always seam

ShaderTileMode REPEAT repeat the shaders image horizontally and

vertically

Color

The Color class defines methods for creating and converting color ints Colors are

represented as packed ints made up of 4 bytes alpha red green blue The

values are unpremultiplied meaning any transparency is stored solely in the

alpha component and not in the color components The components are stored as

follows (alpha ltlt 24) | (red ltlt 16) | (green ltlt 8) | blue Each component ranges

between 0255 with 0 meaning no contribution for that component and 255

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 16

meaning 100 contribution Thus opaque-black would be 0xFF000000 (100

opaque but no contributions from red green or blue) and opaque-white would be

0xFFFFFFFF

Constant

int BLACK int LTGRAY

int BLUE int MAGENTA

int CYAN int RED

int DKGRAY int TRANSPARENT

int GRAY int WHITE

int GREEN int YELLOW

Public Constructors

Color()

Public Methods

static int HSVToColor(float[] hsv)

Convert HSV components to an ARGB color

static int HSVToColor(int alpha float[] hsv)

Convert HSV components to an ARGB color

static void RGBToHSV(int red int green int blue float[] hsv)

Convert RGB components to HSV

static int alpha(int color)

Return the alpha component of a color int

static int argb(int alpha int red int green int blue)

Return a color-int from alpha red green blue components

static int blue(int color)

Return the blue component of a color int

static void colorToHSV(int color float[] hsv)

Convert the argb color to its HSV components

static int green(int color)

Return the green component of a color int

static int parseColor(String colorString)

Parse the color string and return the corresponding color-int

static int red(int color)

Return the red component of a color int

static int rgb(int red int green int blue)

Return a color-int from red green blue components

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 17

Working with Text

Android provide several default fonts typeface and styles Application can also use

custom fonts by including font files as application assets and loading them using

the AssetManger same as recourses

Typeface class

The Typeface class specifies the typeface and intrinsic style of a font This is used

in the paint along with optionally Paint settings like textSize textSkewX

textScaleX to specify how text appears when drawn (and measured)

Constant

int BOLD

int BOLD_ITALIC

int ITALIC

int NORMAL

Fields

public static

final Typeface DEFAULT The default NORMAL typeface object

public static

final Typeface DEFAULT_BOLD The default BOLD typeface object

public static

final Typeface MONOSPACE The NORMAL style of the default monospace typeface

public static

final Typeface SANS_SERIF The NORMAL style of the default sans serif typeface

public static

final Typeface SERIF The NORMAL style of the default serif typeface

Public Methods

static

Typeface

create(String familyName int style)

Create a typeface object given a family name and option style

information

static

Typeface

create(Typeface family int style)

Create a typeface object that best matches the specified existing typeface

and the specified Style

static

Typeface

createFromAsset(AssetManager mgr String path)

Create a new typeface from the specified font data

static

Typeface

createFromFile(String path)

Create a new typeface from the specified font file

static createFromFile(File path)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 18

Typeface Create a new typeface from the specified font file

static

Typeface

defaultFromStyle(int style)

Returns one of the default typeface objects based on the specified style

int getStyle()

Returns the typefaces intrinsic style attributes

final

boolean

isBold()

Returns true if getStyle() has the BOLD bit set

final

boolean

isItalic()

Returns true if getStyle() has the ITALIC bit set

Using Default Fonts and Typefaces

By default Android uses the Sans Serif typeface but Monospace and Serif

typefaces are also available The following code excerpt draws some antialiased text in the default typeface (Sans Serif) to a Canvas

import androidgraphicsCanvas import androidgraphicsColor import androidgraphicsPaint import androidgraphicsTypeface Paint mPaint = new Paint(PaintANTI_ALIAS_FLAG) Typeface mType mPaintsetTextSize(16) mPaintsetTypeface(null) canvasdrawText(ldquoDefault Typefacerdquo 20 20 mPaint) You can instead load a different typeface such as Monotype

Typeface mType = Typefacecreate(TypefaceMONOSPACE TypefaceNORMAL) Perhaps you would prefer italic text in which case you can simply set the style of the typeface and the font family

Typeface mType = Typefacecreate(TypefaceSERIF TypefaceITALIC)

You can set certain properties of a typeface such as antialiasing underlining and strikethrough using the setFlags() method of the Paint object

mPaintsetFlags(PaintUNDERLINE_TEXT_FLAG)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 19

Loading Custom typeface from asset

Typeface mType = TypefacecreateFromAsset(getContext()getAssets()ldquofontschess1ttfrdquo) Example ViewFontjava

package compritesh

import androidcontentContext import androidgraphicsCanvas import androidgraphicsColor import androidgraphicsPaint import androidgraphicsTypeface import androidviewView public class ViewFont extends View Context c public ViewFont(Context context) super(context) c=context protected void onDraw(Canvas canvas) Typeface mType = TypefacecreateFromAsset( cgetAssets() fontsBaroqueScriptttf) Paint p =new Paint(PaintANTI_ALIAS_FLAG) psetTypeface(mType) psetTextSize(20) canvasdrawColor(ColorBLUE) canvasdrawText(Welcome to Android canvasgetWidth()4 canvasgetHeight()3 p)

SampleCustomFontjava package compritesh import androidappActivity import androidgraphicsTypeface import androidosBundle public class SampleCustomFont extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain) setContentView(new ViewFont(this))

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 20

Working with Bitmap and Matrix Bitmap

In computer graphics a bitmap or pixmap is a type of memory organization

or image file format used to store digital images The term bitmap comes from the

computer programming terminology meaning just a map of bits a spatially mapped array of bits Now along with pixmap it commonly refers to the similar

concept of a spatially mapped array of pixels Raster images in general may be referred to as bitmaps or pixmaps whether synthetic or photographic in files or

memory In certain contexts the term bitmap implies one bit per pixel while pixmap

is used for images with multiple bits per pixel

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 21

Shape Drawable in XML

This is a generic shape defined in XML

File location

resdrawablefilenamexml

The filename is used as the resource ID

Compiled resource datatype

Resource pointer to a GradientDrawable

Resource reference

In Java Rdrawablefilename

In XML [package]drawablefilename

Syntax

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=[rectangle | oval | line | ring] gt ltcorners androidradius=integer androidtopLeftRadius=integer androidtopRightRadius=integer androidbottomLeftRadius=integer androidbottomRightRadius=integer gt ltgradient androidangle=integer androidcenterX=integer androidcenterY=integer androidcenterColor=integer androidendColor=color androidgradientRadius=integer androidstartColor=color androidtype=[linear | radial | sweep] androidusesLevel=[true | false] gt ltpadding androidleft=integer androidtop=integer androidright=integer androidbottom=integer gt ltsize androidwidth=integer androidheight=integer gt ltsolid

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 22

androidcolor=color gt ltstroke androidwidth=integer androidcolor=color androiddashWidth=integer androiddashGap=integer gt ltshapegt

Elements

ltshapegt

The shape drawable This must be the root element

Attributes

xmlnsandroid

String Required Defines the XML namespace which must be

httpschemasandroidcomapkresandroid

androidshape

Keyword Defines the type of shape Valid values are

Value Desciption

rectangle A rectangle that fills the containing View This is the default shape

oval An oval shape that fits the dimensions of the containing View

line A horizontal line that spans the width of the containing View This

shape requires the ltstrokegt element to define the width of the line

ring A ring shape

The following attributes are used only when androidshape=ring

androidinnerRadius

Dimension The radius for the inner part of the ring (the hole in the middle)

as a dimension value or dimension resource

androidinnerRadiusRatio

Float The radius for the inner part of the ring expressed as a ratio of the

rings width For instance if androidinnerRadiusRatio=5 then the inner

radius equals the rings width divided by 5 This value is overridden by

androidinnerRadius Default value is 9

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 23

androidthickness

Dimension The thickness of the ring as a dimension value or dimension

resource

androidthicknessRatio

Float The thickness of the ring expressed as a ratio of the rings width For

instance if androidthicknessRatio=2 then the thickness equals the rings

width divided by 2 This value is overridden by androidinnerRadius Default

value is 3

androiduseLevel

Boolean true if this is used as a LevelListDrawable This should normally

be false or your shape may not appear

ltcornersgt

Creates rounded corners for the shape Applies only when the shape is a

rectangle

Attributes

androidradius

Dimension The radius for all corners as a dimension value or dimension

resource This is overridden for each corner by the following attributes

androidtopLeftRadius

Dimension The radius for the top-left corner as a dimension value or

dimension resource

androidtopRightRadius

Dimension The radius for the top-right corner as a dimension value or

dimension resource

androidbottomLeftRadius

Dimension The radius for the bottom-left corner as a dimension value or

dimension resource

androidbottomRightRadius

Dimension The radius for the bottom-right corner as a dimension value or

dimension resource

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 24

Note Every corner must (initially) be provided a corner radius greater than

1 or else no corners are rounded If you want specific corners to not be rounded a work-around is to use androidradius to set a default corner

radius greater than 1 but then override each and every corner with the values you really want providing zero (0dp) where you dont want rounded

corners

ltgradientgt

Specifies a gradient color for the shape

Attributes

androidangle

Integer The angle for the gradient in degrees 0 is left to right 90 is bottom

to top It must be a multiple of 45 Default is 0

androidcenterX

Float The relative X-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterY

Float The relative Y-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterColor

Color Optional color that comes between the start and end colors as a

hexadecimal value or color resource

androidendColor

Color The ending color as a hexadecimal value or color resource

androidgradientRadius

Float The radius for the gradient Only applied when androidtype=radial

androidstartColor

Color The starting color as a hexadecimal value or color resource

androidtype

Keyword The type of gradient pattern to apply Valid values are

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 25

Value Description

linear A linear gradient This is the default

radial A radial gradient The start color is the center color

sweep A sweeping line gradient

androiduseLevel

Boolean true if this is used as a LevelListDrawable

ltpaddinggt

Padding to apply to the containing View element (this pads the position of

the View content not the shape)

Attributes

androidleft

Dimension Left padding as a dimension value or dimension resource

androidtop

Dimension Top padding as a dimension value or dimension resource

androidright

Dimension Right padding as a dimension value or dimension resource

androidbottom

Dimension Bottom padding as a dimension value or dimension resource

ltsizegt

The size of the shape

Attributes

androidheight

Dimension The height of the shape as a dimension value or dimension

resource

androidwidth

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 26

Dimension The width of the shape as a dimension value or dimension

resource

Note The shape scales to the size of the container View proportionate to the

dimensions defined here by default When you use the shape in an ImageView you can restrict scaling by setting the androidscaleType to center

ltsolidgt

A solid color to fill the shape

Attributes

androidcolor

Color The color to apply to the shape as a hexadecimal value or color

resource

ltstrokegt

A stroke line for the shape

Attributes

androidwidth

Dimension The thickness of the line as a dimension value or dimension

resource

androidcolor

Color The color of the line as a hexadecimal value or color resource

androiddashGap

Dimension The distance between line dashes as a dimension value or

dimension resource Only valid if androiddashWidth is set

androiddashWidth

Dimension The size of each dash line as a dimension value or dimension

resource Only valid if androiddashGap is set

Example

XML file saved at resdrawablegradient_boxxml

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 27

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=rectanglegt ltgradient androidstartColor=FFFF0000 androidendColor=80FF00FF androidangle=45gt ltpadding androidleft=7dp androidtop=7dp androidright=7dp androidbottom=7dp gt ltcorners androidradius=8dp gt ltshapegt

This layout XML applies the shape drawable to a View

ltTextView androidbackground=drawablegradient_box androidlayout_height=wrap_content androidlayout_width=wrap_content gt

This application code gets the shape drawable and applies it to a View

Resources res = getResources() Drawable shape = res getDrawable(Rdrawablegradient_box)

TextView tv = (TextView)findViewByID(Ridtextview) tvsetBackground(shape)

Page 2: Android graphics mca 5th

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 2

Draw with a Canvas

When youre writing an application in which you would like to perform specialized

drawing andor control the animation of graphics you should do so by drawing

through a Canvas A Canvas works for you as a pretense or interface to the

actual surface upon which your graphics will be drawn mdash it holds all of your

draw calls Via the Canvas your drawing is actually performed upon an

underlying Bitmap which is placed into the window

In the event that youre drawing within the onDraw() callback method the Canvas

is provided for you and you need only place your drawing calls upon it You can

also acquire a Canvas from SurfaceHolderlockCanvas() when dealing with a

SurfaceView object (Both of these scenarios are discussed in the following

sections) However if you need to create a new Canvas then you must define

the Bitmap upon which drawing will actually be performed The Bitmap is always

required for a Canvas You can set up a new Canvas like this

Bitmap b = BitmapcreateBitmap(100 100 BitmapConfigARGB_8888)

Canvas c = new Canvas(b)

Now your Canvas will draw onto the defined Bitmap After drawing upon it with

the Canvas you can then carry your Bitmap to another Canvas with one of

the CanvasdrawBitmap(Bitmap) methods Its recommended that you

ultimately draw your final graphics through a Canvas offered to you

by ViewonDraw() or SurfaceHolderlockCanvas() (see the following sections)

The Canvas class has its own set of drawing methods that you can use

like drawBitmap() drawRect()drawText() and many more Other classes

that you might use also have draw() methods For example youll probably have

some Drawable objects that you want to put on the Canvas Drawable has its

own draw() method that takes your Canvas as an argument

Draw On a View

If your application does not require a significant amount of processing or frame-

rate speed (perhaps for a chess game a snake game or another slowly-animated

application) then you should consider creating a custom View component and

drawing with a Canvas in ViewonDraw() The most convenient aspect of doing so

is that the Android framework will provide you with a pre-defined Canvas to which

you will place your drawing calls

To start extend the View class (or descendant thereof) and define

the onDraw() callback method This method will be called by the Android

framework to request that your View draw itself This is where you will perform all

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 3

your calls to draw through the Canvas which is passed to you through

the onDraw() callback

The Android framework will only call onDraw() as necessary Each time that your

application is prepared to be drawn you must request your View be invalidated by

calling invalidate() This indicates that youd like your View to be drawn and

Android will then call your onDraw() method (though is not guaranteed that the

callback will be instantaneous)

Inside your View components onDraw() use the Canvas given to you for all your

drawing using various Canvasdraw() methods or other class draw() methods

that take your Canvas as an argument Once your onDraw() is complete the

Android framework will use your Canvas to draw a Bitmap handled by the system

Note In order to request an invalidate from a thread other than your main

Activitys thread you must call postInvalidate()

Draw On a SurfaceView

The SurfaceView is a special subclass of View that offers a dedicated drawing surface within the View hierarchy The aim is to offer this drawing surface to an applications secondary thread so that the application isnt required to wait until

the systems View hierarchy is ready to draw Instead a secondary thread that has reference to a SurfaceView can draw to its own Canvas at its own pace

To begin you need to create a new class that extends SurfaceView The class

should also implement SurfaceHolderCallback This subclass is an interface that will notify you with information about the underlying Surface such as when it is created changed or destroyed These events are important so that you know

when you can start drawing whether you need to make adjustments based on new surface properties and when to stop drawing and potentially kill some tasks

Inside your SurfaceView class is also a good place to define your secondary Thread class which will perform all the drawing procedures to your Canvas

Instead of handling the Surface object directly you should handle it via a SurfaceHolder So when your SurfaceView is initialized get the SurfaceHolder by

calling getHolder() You should then notify the SurfaceHolder that youd like to receive SurfaceHolder callbacks (from SurfaceHolderCallback) by calling

addCallback() (pass it this) Then override each of the SurfaceHolderCallback methods inside your SurfaceView class

In order to draw to the Surface Canvas from within your second thread you must pass the thread your SurfaceHandler and retrieve the Canvas with lockCanvas()

You can now take the Canvas given to you by the SurfaceHolder and do your necessary drawing upon it Once youre done drawing with the Canvas call

unlockCanvasAndPost() passing it your Canvas object The Surface will now draw

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 4

the Canvas as you left it Perform this sequence of locking and unlocking the canvas each time you want to redraw

Note On each pass you retrieve the Canvas from the SurfaceHolder the previous state of the Canvas will be retained In order to properly animate your graphics

you must re-paint the entire surface For example you can clear the previous state of the Canvas by filling in a color with drawColor() or setting a background image with drawBitmap() Otherwise you will see traces of the drawings you

previously performed

2D Graphics

Android offers a custom 2D graphics library for drawing and animating shapes

and images Theandroidgraphicsdrawable andandroidviewanimation packages

are where youll find the common classes used for drawing and animating in two-

dimensions

This document offers an introduction to drawing graphics in your Android

application Well discuss the basics of using Drawable objects to draw graphics

how to use a couple subclasses of the Drawable class and how to create

animations that either tween (move stretch rotate) a single graphic or animate a

series of graphics (like a roll of film)

Drawables

A Drawable is a general abstraction for something that can be drawn Youll

discover that the Drawable class extends to define a variety of specific kinds of

drawable graphics

including BitmapDrawable ShapeDrawable PictureDrawableLayerDrawable and

several more Of course you can also extend these to define your own custom

Drawable objects that behave in unique ways

There are three ways to define and instantiate a Drawable using an image saved

in your project resources using an XML file that defines the Drawable properties

or using the normal class constructors Below well discuss each the first two

techniques (using constructors is nothing new for an experienced developer)

Creating from resource images

A simple way to add graphics to your application is by referencing an image file

from your project resources Supported file types are PNG (preferred) JPG

(acceptable) and GIF (discouraged) This technique would obviously be preferred

for application icons logos or other graphics such as those used in a game

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 5

To use an image resource just add your file to the resdrawable directory of your

project From there you can reference it from your code or your XML layout

Either way it is referred using a resource ID which is the file name without the

file type extension (Eg my_imagepng is referenced as my_image)

Example code

The following code snippet demonstrates how to build an ImageView that uses an

image from drawable resources and add it to the layout

LinearLayout mLinearLayout

protected void onCreate(Bundle savedInstanceState)

superonCreate(savedInstanceState) Create a LinearLayout in which to add the ImageView

mLinearLayout = new LinearLayout(this) Instantiate an ImageView and define its properties

ImageView i = new ImageView(this) isetImageResource(Rdrawablemy_image)

isetAdjustViewBounds(true) set the ImageView bounds to match the Drawables dimensions isetLayoutParams(new

GalleryLayoutParams(LayoutParamsWRAP_CONTENT LayoutParamsWRAP_CONTENT))

Add the ImageView to the layout and set the layout as the content view mLinearLayoutaddView(i)

setContentView(mLinearLayout)

In other cases you may want to handle your image resource as a Drawable object

To do so create a Drawable from the resource like so

Resources res = mContextgetResources()

Drawable myImage = resgetDrawable(Rdrawablemy_image)

Example XML

The XML snippet below shows how to add a resource Drawable to an ImageView in

the XML layout (with some red tint just for fun)

ltImageView androidlayout_width=wrap_content

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 6

androidlayout_height=wrap_content androidtint=55ff0000

androidsrc=drawablemy_imagegt

Creating from resource XML

By now you should be familiar with Androids principles of developing a User

Interface Hence you understand the power and flexibility inherent in defining

objects in XML This philosophy caries over from Views to Drawables If there is a

Drawable object that youd like to create which is not initially dependent on

variables defined by your application code or user interaction then defining the

Drawable in XML is a good option Even if you expect your Drawable to change its

properties during the users experience with your application you should consider

defining the object in XML as you can always modify properties once it is

instantiated

Once youve defined your Drawable in XML save the file in

the resdrawable directory of your project Then retrieve and instantiate the

object by calling ResourcesgetDrawable() passing it the resource ID of your XML

file (See the example below)

Any Drawable subclass that supports the inflate() method can be defined in XML

and instantiated by your application Each Drawable that supports XML inflation

utilizes specific XML attributes that help define the object properties (see the class

reference to see what these are) See the class documentation for each Drawable

subclass for information on how to define it in XML

Example

Heres some XML that defines a TransitionDrawable

lttransition xmlnsandroid=httpschemasandroidcomapkresandroidgt ltitem androiddrawable=drawableimage_expandgt ltitem androiddrawable=drawableimage_collapsegt

lttransitiongt

With this XML saved in the file resdrawableexpand_collapsexml the following

code will instantiate the TransitionDrawable and set it as the content of an

ImageView

Resources res = mContextgetResources() TransitionDrawable transition = (TransitionDrawable)

resgetDrawable(Rdrawableexpand_collapse)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 7

ImageView image = (ImageView) findViewById(Ridtoggle_image)

imagesetImageDrawable(transition)

Then this transition can be run forward (for 1 second) with

transitionstartTransition(1000)

Canvas class

The Canvas class holds the draw calls To draw something you need 4 basic

components A Bitmap to hold the pixels a Canvas to host the draw calls (writing

into the bitmap) a drawing primitive (eg Rect Path text Bitmap) and a paint (to

describe the colors and styles for the drawing)

Public Constructors

Canvas() Construct an empty raster canvas

Canvas(Bitmap bitmap) Construct a canvas with the specified bitmap to draw into

Public Methods

void drawArc(RectF oval float startAngle float sweepAngle boolean useCenter Paint paint)

Draw the specified arc which will be scaled to fit inside the specified

oval

void drawBitmap(Bitmap bitmap float left float top Paint paint) Draw the specified bitmap with its topleft corner at (xy) using the

specified paint transformed by the current matrix

void drawCircle(float cx float cy float radius Paint paint) Draw the specified circle using the specified paint

void drawColor(int color) Fill the entire canvas bitmap (restricted to the current clip) with the specified color using srcover porterduff mode

void drawLine(float startX float startY float stopX float stopY Paint paint)

Draw a line segment with the specified start and stop xy coordinates using the specified paint

void drawLines(float[] pts Paint paint)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 8

void drawLines(float[] pts int offset int count Paint paint)

Draw a series of lines

void drawOval(RectF oval Paint paint)

Draw the specified oval using the specified paint

void drawPaint(Paint paint)

Fill the entire canvas bitmap (restricted to the current clip) with the specified paint

void drawPicture(Picture picture) Save the canvas state draw the picture and restore the canvas state

void drawPicture(Picture picture Rect dst) Draw the picture stretched to fit into the dst rectangle

void drawPoint(float x float y Paint paint) Helper for drawPoints() for drawing a single point

void drawPoints(float[] pts int offset int count Paint paint) Draw a series of points

void drawPoints(float[] pts Paint paint) Helper for drawPoints() that assumes you want to draw the entire

array

void drawPosText(char[] text int index int count float[] pos Paint paint)

Draw the text in the array with each characters origin specified by the pos array

void drawPosText(String text float[] pos Paint paint) Draw the text in the array with each characters origin specified by the pos array

void drawRGB(int r int g int b) Fill the entire canvas bitmap (restricted to the current clip) with the

specified RGB color using srcover porterduff mode

void drawRect(float left float top float right float bottom Paint paint)

Draw the specified Rect using the specified paint

void drawRect(RectF rect Paint paint)

Draw the specified Rect using the specified paint

void drawRect(Rect r Paint paint)

Draw the specified Rect using the specified Paint

void drawRoundRect(RectF rect float rx float ry Paint paint)

Draw the specified round-rect using the specified paint

void drawText(String text float x float y Paint paint)

Draw the text with origin at (xy) using the specified paint

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 9

void drawText(CharSequence text int start int end float x float

y Paint paint) Draw the specified range of text specified by startend with its origin at (xy) in the specified Paint

void drawText(char[] text int index int count float x float y Paint paint) Draw the text with origin at (xy) using the specified paint

void drawText(String text int start int end float x float y Paint paint) Draw the text with origin at (xy) using the specified paint

void drawTextOnPath(String text Path path float hOffset float vOffset Paint paint)

Draw the text with origin at (xy) using the specified paint along the specified path

void drawTextOnPath(char[] text int index int count Path path float hOffset float vOffset Paint paint)

Draw the text with origin at (xy) using the specified paint along the specified path

int getHeight() Returns the height of the current drawing layer

void getMatrix(Matrix ctm) Return in ctm the current transformation matrix

final Matrix

getMatrix() Return a new matrix with a copy of the canvas current transformation matrix

int getWidth() Returns the width of the current drawing layer

void rotate(float degrees) Preconcat the current matrix with the specified rotation

final void

rotate(float degrees float px float py) Preconcat the current matrix with the specified rotation

void scale(float sx float sy) Preconcat the current matrix with the specified scale

final

void scale(float sx float sy float px float py)

Preconcat the current matrix with the specified scale

void setBitmap(Bitmap bitmap)

Specify a bitmap for the canvas to draw into

void translate(float dx float dy)

Preconcat the current matrix with the specified translation

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 10

Paint class

The Paint class holds the style and color information about how to draw

geometries text and bitmaps

Paint Styles

public static final PaintStyle FILL

Geometry and text drawn with this style will be filled ignoring all stroke-related

settings in the paint

public static final PaintStyle FILL_AND_STROKE

Geometry and text drawn with this style will be both filled and stroked at the same time respecting the stroke-related fields on the paint This mode can give unexpected results if the geometry is oriented counter-clockwise This restriction

does not apply to either FILL or STROKE

public static final PaintStyle STROKE

Geometry and text drawn with this style will be stroked respecting the stroke-related fields on the paint

Public Constructors

Paint()

Create a new paint with default settings

Paint(int flags)

Create a new paint with the specified flags

Paint(Paint paint)

Create a new paint initialized with the attributes in the specified paint parameter

Public Methods

int getAlpha()

Helper to getColor() that just returns the colors alpha value

int getColor()

Return the paints color

ColorFilter getColorFilter()

Get the paints colorfilter (maybe be null)

boolean

getFillPath(Path src Path dst)

Applies anyall effects (patheffect stroking) to src returning

the result in dst

int getFlags()

Return the paints flags

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 11

PaintFontMetrics

getFontMetrics()

Allocates a new FontMetrics object and then calls

getFontMetrics(fm) with it returning the object

int

getFontMetricsInt(PaintFontMetricsInt fmi)

Return the fonts interline spacing given the Paints settings

for typeface textSize etc

float

getFontSpacing()

Return the recommend line spacing based on the current

typeface and text size

MaskFilter getMaskFilter()

Get the paints maskfilter object

Shader getShader()

Get the paints shader object

PaintStyle

getStyle()

Return the paints style used for controlling how primitives

geometries are interpreted (except for drawBitmap which

always assumes FILL_STYLE)

PaintAlign getTextAlign()

Return the paints Align value for drawing text

void

getTextBounds(char[] text int index int count Rect bounds)

Return in bounds (allocated by the caller) the smallest

rectangle that encloses all of the characters with an implied

origin at (00)

void

getTextBounds(String text int start int end Rect bounds)

Return in bounds (allocated by the caller) the smallest

rectangle that encloses all of the characters with an implied

origin at (00)

void

getTextPath(String text int start int end float x float y Path

path)

Return the path (outline) for the specified text

void

getTextPath(char[] text int index int count float x float y

Path path)

Return the path (outline) for the specified text

float getTextScaleX()

Return the paints horizontal scale factor for text

float getTextSize()

Return the paints text size

int getTextWidths(String text float[] widths)

Return the advance widths for the characters in the string

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 12

int

getTextWidths(CharSequence text int start int end float[]

widths)

Return the advance widths for the characters in the string

int getTextWidths(String text int start int end float[] widths)

Return the advance widths for the characters in the string

int getTextWidths(char[] text int index int count float[] widths)

Return the advance widths for the characters in the string

Typeface getTypeface()

Get the paints typeface object

final boolean

isAntiAlias()

Helper for getFlags() returning true if ANTI_ALIAS_FLAG bit is

set AntiAliasing smooths out the edges of what is being

drawn but is has no impact on the interior of the shape

final boolean

isStrikeThruText()

Helper for getFlags() returning true if

STRIKE_THRU_TEXT_FLAG bit is set

final boolean

isSubpixelText()

Helper for getFlags() returning true if SUBPIXEL_TEXT_FLAG

bit is set

final boolean

isUnderlineText()

Helper for getFlags() returning true if

UNDERLINE_TEXT_FLAG bit is set

float measureText(String text)

Return the width of the text

float measureText(CharSequence text int start int end)

Return the width of the text

float measureText(String text int start int end)

Return the width of the text

float measureText(char[] text int index int count)

Return the width of the text

void reset()

Restores the paint to its default settings

void set(Paint src)

Copy the fields from src into this paint

void

setARGB(int a int r int g int b)

Helper to setColor() that takes argb and constructs the

color int

void setAlpha(int a)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 13

Helper to setColor() that only assigns the colors alpha value

leaving its rgb values unchanged

void

setAntiAlias(boolean aa)

Helper for setFlags() setting or clearing the ANTI_ALIAS_FLAG

bit AntiAliasing smooths out the edges of what is being drawn

but is has no impact on the interior of the shape

void setColor(int color)

Set the paints color

ColorFilter setColorFilter(ColorFilter filter)

Set or clear the paints colorfilter returning the parameter

void

setFakeBoldText(boolean fakeBoldText)

Helper for setFlags() setting or clearing the

FAKE_BOLD_TEXT_FLAG bit

void setFlags(int flags)

Set the paints flags

PathEffect setPathEffect(PathEffect effect)

Set or clear the patheffect object

Shader setShader(Shader shader)

Set or clear the shader object

void

setShadowLayer(float radius float dx float dy int color)

This draws a shadow layer below the main layer with the

specified offset and color and blur radius

void

setStrikeThruText(boolean strikeThruText)

Helper for setFlags() setting or clearing the

STRIKE_THRU_TEXT_FLAG bit

void

setStyle(PaintStyle style)

Set the paints style used for controlling how primitives

geometries are interpreted (except for drawBitmap which

always assumes Fill)

void

setSubpixelText(boolean subpixelText)

Helper for setFlags() setting or clearing the

SUBPIXEL_TEXT_FLAG bit

void setTextAlign(PaintAlign align)

Set the paints text alignment

void setTextSize(float textSize)

Set the paints text size

void setTextSkewX(float skewX)

Set the paints horizontal skew factor for text

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 14

Typeface setTypeface(Typeface typeface)

Set or clear the typeface object

void

setUnderlineText(boolean underlineText)

Helper for setFlags() setting or clearing the

UNDERLINE_TEXT_FLAG bit

Types of Gradient

1 Linear Gradient

public LinearGradient (float x0 float y0 float x1 float y1 int[] colors float[]

positions ShaderTileMode tile)

Create a shader that draws a linear gradient along a line

Parameters

x0 The x-coordinate for the start of the gradient line

y0 The y-coordinate for the start of the gradient line

x1 The x-coordinate for the end of the gradient line

y1 The y-coordinate for the end of the gradient line

colors The colors to be distributed along the gradient line

positions

May be null The relative positions [01] of each corresponding color in

the colors array If this is null the the colors are distributed evenly

along the gradient line

tile The Shader tiling mode

2 Sweep Gradient

public SweepGradient (float cx float cy int[] colors float[] positions)

A subclass of Shader that draws a sweep gradient around a center point

Parameters

cx The x-coordinate of the center

cy The y-coordinate of the center

colors The colors to be distributed between around the center There must be

at least 2 colors in the array

positions

May be NULL The relative position of each corresponding color in the

colors array beginning with 0 and ending with 10 If the values are not

monotonic the drawing may produce unexpected results If positions is

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 15

NULL then the colors are automatically spaced evenly

3 Radial Gradient

public RadialGradient (float x float y float radius int[] colors float[] positions

ShaderTileMode tile)

Create a shader that draws a radial gradient given the center and radius

Parameters

x The x-coordinate of the center of the radius

y The y-coordinate of the center of the radius

radius Must be positive The radius of the circle for this gradient

colors The colors to be distributed between the center and edge of the circle

positions

May be NULL The relative position of each corresponding color in the

colors array If this is NULL the the colors are distributed evenly

between the center and edge of the circle

tile The Shader tiling mode

Shader Class

Shader is the based class for objects that return horizontal spans of colors during

drawing A subclass of Shader is installed in a Paint calling

paintsetShader(shader) After that any object (other than a bitmap) that is drawn

with that paint will get its color(s) from the shader

ShaderTileMode CLAMP replicate the edge color if the shader draws

outside of its original bounds

ShaderTileMode MIRROR repeat the shaders image horizontally and

vertically alternating mirror images so that adjacent images always seam

ShaderTileMode REPEAT repeat the shaders image horizontally and

vertically

Color

The Color class defines methods for creating and converting color ints Colors are

represented as packed ints made up of 4 bytes alpha red green blue The

values are unpremultiplied meaning any transparency is stored solely in the

alpha component and not in the color components The components are stored as

follows (alpha ltlt 24) | (red ltlt 16) | (green ltlt 8) | blue Each component ranges

between 0255 with 0 meaning no contribution for that component and 255

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 16

meaning 100 contribution Thus opaque-black would be 0xFF000000 (100

opaque but no contributions from red green or blue) and opaque-white would be

0xFFFFFFFF

Constant

int BLACK int LTGRAY

int BLUE int MAGENTA

int CYAN int RED

int DKGRAY int TRANSPARENT

int GRAY int WHITE

int GREEN int YELLOW

Public Constructors

Color()

Public Methods

static int HSVToColor(float[] hsv)

Convert HSV components to an ARGB color

static int HSVToColor(int alpha float[] hsv)

Convert HSV components to an ARGB color

static void RGBToHSV(int red int green int blue float[] hsv)

Convert RGB components to HSV

static int alpha(int color)

Return the alpha component of a color int

static int argb(int alpha int red int green int blue)

Return a color-int from alpha red green blue components

static int blue(int color)

Return the blue component of a color int

static void colorToHSV(int color float[] hsv)

Convert the argb color to its HSV components

static int green(int color)

Return the green component of a color int

static int parseColor(String colorString)

Parse the color string and return the corresponding color-int

static int red(int color)

Return the red component of a color int

static int rgb(int red int green int blue)

Return a color-int from red green blue components

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 17

Working with Text

Android provide several default fonts typeface and styles Application can also use

custom fonts by including font files as application assets and loading them using

the AssetManger same as recourses

Typeface class

The Typeface class specifies the typeface and intrinsic style of a font This is used

in the paint along with optionally Paint settings like textSize textSkewX

textScaleX to specify how text appears when drawn (and measured)

Constant

int BOLD

int BOLD_ITALIC

int ITALIC

int NORMAL

Fields

public static

final Typeface DEFAULT The default NORMAL typeface object

public static

final Typeface DEFAULT_BOLD The default BOLD typeface object

public static

final Typeface MONOSPACE The NORMAL style of the default monospace typeface

public static

final Typeface SANS_SERIF The NORMAL style of the default sans serif typeface

public static

final Typeface SERIF The NORMAL style of the default serif typeface

Public Methods

static

Typeface

create(String familyName int style)

Create a typeface object given a family name and option style

information

static

Typeface

create(Typeface family int style)

Create a typeface object that best matches the specified existing typeface

and the specified Style

static

Typeface

createFromAsset(AssetManager mgr String path)

Create a new typeface from the specified font data

static

Typeface

createFromFile(String path)

Create a new typeface from the specified font file

static createFromFile(File path)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 18

Typeface Create a new typeface from the specified font file

static

Typeface

defaultFromStyle(int style)

Returns one of the default typeface objects based on the specified style

int getStyle()

Returns the typefaces intrinsic style attributes

final

boolean

isBold()

Returns true if getStyle() has the BOLD bit set

final

boolean

isItalic()

Returns true if getStyle() has the ITALIC bit set

Using Default Fonts and Typefaces

By default Android uses the Sans Serif typeface but Monospace and Serif

typefaces are also available The following code excerpt draws some antialiased text in the default typeface (Sans Serif) to a Canvas

import androidgraphicsCanvas import androidgraphicsColor import androidgraphicsPaint import androidgraphicsTypeface Paint mPaint = new Paint(PaintANTI_ALIAS_FLAG) Typeface mType mPaintsetTextSize(16) mPaintsetTypeface(null) canvasdrawText(ldquoDefault Typefacerdquo 20 20 mPaint) You can instead load a different typeface such as Monotype

Typeface mType = Typefacecreate(TypefaceMONOSPACE TypefaceNORMAL) Perhaps you would prefer italic text in which case you can simply set the style of the typeface and the font family

Typeface mType = Typefacecreate(TypefaceSERIF TypefaceITALIC)

You can set certain properties of a typeface such as antialiasing underlining and strikethrough using the setFlags() method of the Paint object

mPaintsetFlags(PaintUNDERLINE_TEXT_FLAG)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 19

Loading Custom typeface from asset

Typeface mType = TypefacecreateFromAsset(getContext()getAssets()ldquofontschess1ttfrdquo) Example ViewFontjava

package compritesh

import androidcontentContext import androidgraphicsCanvas import androidgraphicsColor import androidgraphicsPaint import androidgraphicsTypeface import androidviewView public class ViewFont extends View Context c public ViewFont(Context context) super(context) c=context protected void onDraw(Canvas canvas) Typeface mType = TypefacecreateFromAsset( cgetAssets() fontsBaroqueScriptttf) Paint p =new Paint(PaintANTI_ALIAS_FLAG) psetTypeface(mType) psetTextSize(20) canvasdrawColor(ColorBLUE) canvasdrawText(Welcome to Android canvasgetWidth()4 canvasgetHeight()3 p)

SampleCustomFontjava package compritesh import androidappActivity import androidgraphicsTypeface import androidosBundle public class SampleCustomFont extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain) setContentView(new ViewFont(this))

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 20

Working with Bitmap and Matrix Bitmap

In computer graphics a bitmap or pixmap is a type of memory organization

or image file format used to store digital images The term bitmap comes from the

computer programming terminology meaning just a map of bits a spatially mapped array of bits Now along with pixmap it commonly refers to the similar

concept of a spatially mapped array of pixels Raster images in general may be referred to as bitmaps or pixmaps whether synthetic or photographic in files or

memory In certain contexts the term bitmap implies one bit per pixel while pixmap

is used for images with multiple bits per pixel

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 21

Shape Drawable in XML

This is a generic shape defined in XML

File location

resdrawablefilenamexml

The filename is used as the resource ID

Compiled resource datatype

Resource pointer to a GradientDrawable

Resource reference

In Java Rdrawablefilename

In XML [package]drawablefilename

Syntax

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=[rectangle | oval | line | ring] gt ltcorners androidradius=integer androidtopLeftRadius=integer androidtopRightRadius=integer androidbottomLeftRadius=integer androidbottomRightRadius=integer gt ltgradient androidangle=integer androidcenterX=integer androidcenterY=integer androidcenterColor=integer androidendColor=color androidgradientRadius=integer androidstartColor=color androidtype=[linear | radial | sweep] androidusesLevel=[true | false] gt ltpadding androidleft=integer androidtop=integer androidright=integer androidbottom=integer gt ltsize androidwidth=integer androidheight=integer gt ltsolid

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 22

androidcolor=color gt ltstroke androidwidth=integer androidcolor=color androiddashWidth=integer androiddashGap=integer gt ltshapegt

Elements

ltshapegt

The shape drawable This must be the root element

Attributes

xmlnsandroid

String Required Defines the XML namespace which must be

httpschemasandroidcomapkresandroid

androidshape

Keyword Defines the type of shape Valid values are

Value Desciption

rectangle A rectangle that fills the containing View This is the default shape

oval An oval shape that fits the dimensions of the containing View

line A horizontal line that spans the width of the containing View This

shape requires the ltstrokegt element to define the width of the line

ring A ring shape

The following attributes are used only when androidshape=ring

androidinnerRadius

Dimension The radius for the inner part of the ring (the hole in the middle)

as a dimension value or dimension resource

androidinnerRadiusRatio

Float The radius for the inner part of the ring expressed as a ratio of the

rings width For instance if androidinnerRadiusRatio=5 then the inner

radius equals the rings width divided by 5 This value is overridden by

androidinnerRadius Default value is 9

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 23

androidthickness

Dimension The thickness of the ring as a dimension value or dimension

resource

androidthicknessRatio

Float The thickness of the ring expressed as a ratio of the rings width For

instance if androidthicknessRatio=2 then the thickness equals the rings

width divided by 2 This value is overridden by androidinnerRadius Default

value is 3

androiduseLevel

Boolean true if this is used as a LevelListDrawable This should normally

be false or your shape may not appear

ltcornersgt

Creates rounded corners for the shape Applies only when the shape is a

rectangle

Attributes

androidradius

Dimension The radius for all corners as a dimension value or dimension

resource This is overridden for each corner by the following attributes

androidtopLeftRadius

Dimension The radius for the top-left corner as a dimension value or

dimension resource

androidtopRightRadius

Dimension The radius for the top-right corner as a dimension value or

dimension resource

androidbottomLeftRadius

Dimension The radius for the bottom-left corner as a dimension value or

dimension resource

androidbottomRightRadius

Dimension The radius for the bottom-right corner as a dimension value or

dimension resource

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 24

Note Every corner must (initially) be provided a corner radius greater than

1 or else no corners are rounded If you want specific corners to not be rounded a work-around is to use androidradius to set a default corner

radius greater than 1 but then override each and every corner with the values you really want providing zero (0dp) where you dont want rounded

corners

ltgradientgt

Specifies a gradient color for the shape

Attributes

androidangle

Integer The angle for the gradient in degrees 0 is left to right 90 is bottom

to top It must be a multiple of 45 Default is 0

androidcenterX

Float The relative X-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterY

Float The relative Y-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterColor

Color Optional color that comes between the start and end colors as a

hexadecimal value or color resource

androidendColor

Color The ending color as a hexadecimal value or color resource

androidgradientRadius

Float The radius for the gradient Only applied when androidtype=radial

androidstartColor

Color The starting color as a hexadecimal value or color resource

androidtype

Keyword The type of gradient pattern to apply Valid values are

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 25

Value Description

linear A linear gradient This is the default

radial A radial gradient The start color is the center color

sweep A sweeping line gradient

androiduseLevel

Boolean true if this is used as a LevelListDrawable

ltpaddinggt

Padding to apply to the containing View element (this pads the position of

the View content not the shape)

Attributes

androidleft

Dimension Left padding as a dimension value or dimension resource

androidtop

Dimension Top padding as a dimension value or dimension resource

androidright

Dimension Right padding as a dimension value or dimension resource

androidbottom

Dimension Bottom padding as a dimension value or dimension resource

ltsizegt

The size of the shape

Attributes

androidheight

Dimension The height of the shape as a dimension value or dimension

resource

androidwidth

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 26

Dimension The width of the shape as a dimension value or dimension

resource

Note The shape scales to the size of the container View proportionate to the

dimensions defined here by default When you use the shape in an ImageView you can restrict scaling by setting the androidscaleType to center

ltsolidgt

A solid color to fill the shape

Attributes

androidcolor

Color The color to apply to the shape as a hexadecimal value or color

resource

ltstrokegt

A stroke line for the shape

Attributes

androidwidth

Dimension The thickness of the line as a dimension value or dimension

resource

androidcolor

Color The color of the line as a hexadecimal value or color resource

androiddashGap

Dimension The distance between line dashes as a dimension value or

dimension resource Only valid if androiddashWidth is set

androiddashWidth

Dimension The size of each dash line as a dimension value or dimension

resource Only valid if androiddashGap is set

Example

XML file saved at resdrawablegradient_boxxml

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 27

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=rectanglegt ltgradient androidstartColor=FFFF0000 androidendColor=80FF00FF androidangle=45gt ltpadding androidleft=7dp androidtop=7dp androidright=7dp androidbottom=7dp gt ltcorners androidradius=8dp gt ltshapegt

This layout XML applies the shape drawable to a View

ltTextView androidbackground=drawablegradient_box androidlayout_height=wrap_content androidlayout_width=wrap_content gt

This application code gets the shape drawable and applies it to a View

Resources res = getResources() Drawable shape = res getDrawable(Rdrawablegradient_box)

TextView tv = (TextView)findViewByID(Ridtextview) tvsetBackground(shape)

Page 3: Android graphics mca 5th

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 3

your calls to draw through the Canvas which is passed to you through

the onDraw() callback

The Android framework will only call onDraw() as necessary Each time that your

application is prepared to be drawn you must request your View be invalidated by

calling invalidate() This indicates that youd like your View to be drawn and

Android will then call your onDraw() method (though is not guaranteed that the

callback will be instantaneous)

Inside your View components onDraw() use the Canvas given to you for all your

drawing using various Canvasdraw() methods or other class draw() methods

that take your Canvas as an argument Once your onDraw() is complete the

Android framework will use your Canvas to draw a Bitmap handled by the system

Note In order to request an invalidate from a thread other than your main

Activitys thread you must call postInvalidate()

Draw On a SurfaceView

The SurfaceView is a special subclass of View that offers a dedicated drawing surface within the View hierarchy The aim is to offer this drawing surface to an applications secondary thread so that the application isnt required to wait until

the systems View hierarchy is ready to draw Instead a secondary thread that has reference to a SurfaceView can draw to its own Canvas at its own pace

To begin you need to create a new class that extends SurfaceView The class

should also implement SurfaceHolderCallback This subclass is an interface that will notify you with information about the underlying Surface such as when it is created changed or destroyed These events are important so that you know

when you can start drawing whether you need to make adjustments based on new surface properties and when to stop drawing and potentially kill some tasks

Inside your SurfaceView class is also a good place to define your secondary Thread class which will perform all the drawing procedures to your Canvas

Instead of handling the Surface object directly you should handle it via a SurfaceHolder So when your SurfaceView is initialized get the SurfaceHolder by

calling getHolder() You should then notify the SurfaceHolder that youd like to receive SurfaceHolder callbacks (from SurfaceHolderCallback) by calling

addCallback() (pass it this) Then override each of the SurfaceHolderCallback methods inside your SurfaceView class

In order to draw to the Surface Canvas from within your second thread you must pass the thread your SurfaceHandler and retrieve the Canvas with lockCanvas()

You can now take the Canvas given to you by the SurfaceHolder and do your necessary drawing upon it Once youre done drawing with the Canvas call

unlockCanvasAndPost() passing it your Canvas object The Surface will now draw

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 4

the Canvas as you left it Perform this sequence of locking and unlocking the canvas each time you want to redraw

Note On each pass you retrieve the Canvas from the SurfaceHolder the previous state of the Canvas will be retained In order to properly animate your graphics

you must re-paint the entire surface For example you can clear the previous state of the Canvas by filling in a color with drawColor() or setting a background image with drawBitmap() Otherwise you will see traces of the drawings you

previously performed

2D Graphics

Android offers a custom 2D graphics library for drawing and animating shapes

and images Theandroidgraphicsdrawable andandroidviewanimation packages

are where youll find the common classes used for drawing and animating in two-

dimensions

This document offers an introduction to drawing graphics in your Android

application Well discuss the basics of using Drawable objects to draw graphics

how to use a couple subclasses of the Drawable class and how to create

animations that either tween (move stretch rotate) a single graphic or animate a

series of graphics (like a roll of film)

Drawables

A Drawable is a general abstraction for something that can be drawn Youll

discover that the Drawable class extends to define a variety of specific kinds of

drawable graphics

including BitmapDrawable ShapeDrawable PictureDrawableLayerDrawable and

several more Of course you can also extend these to define your own custom

Drawable objects that behave in unique ways

There are three ways to define and instantiate a Drawable using an image saved

in your project resources using an XML file that defines the Drawable properties

or using the normal class constructors Below well discuss each the first two

techniques (using constructors is nothing new for an experienced developer)

Creating from resource images

A simple way to add graphics to your application is by referencing an image file

from your project resources Supported file types are PNG (preferred) JPG

(acceptable) and GIF (discouraged) This technique would obviously be preferred

for application icons logos or other graphics such as those used in a game

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 5

To use an image resource just add your file to the resdrawable directory of your

project From there you can reference it from your code or your XML layout

Either way it is referred using a resource ID which is the file name without the

file type extension (Eg my_imagepng is referenced as my_image)

Example code

The following code snippet demonstrates how to build an ImageView that uses an

image from drawable resources and add it to the layout

LinearLayout mLinearLayout

protected void onCreate(Bundle savedInstanceState)

superonCreate(savedInstanceState) Create a LinearLayout in which to add the ImageView

mLinearLayout = new LinearLayout(this) Instantiate an ImageView and define its properties

ImageView i = new ImageView(this) isetImageResource(Rdrawablemy_image)

isetAdjustViewBounds(true) set the ImageView bounds to match the Drawables dimensions isetLayoutParams(new

GalleryLayoutParams(LayoutParamsWRAP_CONTENT LayoutParamsWRAP_CONTENT))

Add the ImageView to the layout and set the layout as the content view mLinearLayoutaddView(i)

setContentView(mLinearLayout)

In other cases you may want to handle your image resource as a Drawable object

To do so create a Drawable from the resource like so

Resources res = mContextgetResources()

Drawable myImage = resgetDrawable(Rdrawablemy_image)

Example XML

The XML snippet below shows how to add a resource Drawable to an ImageView in

the XML layout (with some red tint just for fun)

ltImageView androidlayout_width=wrap_content

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 6

androidlayout_height=wrap_content androidtint=55ff0000

androidsrc=drawablemy_imagegt

Creating from resource XML

By now you should be familiar with Androids principles of developing a User

Interface Hence you understand the power and flexibility inherent in defining

objects in XML This philosophy caries over from Views to Drawables If there is a

Drawable object that youd like to create which is not initially dependent on

variables defined by your application code or user interaction then defining the

Drawable in XML is a good option Even if you expect your Drawable to change its

properties during the users experience with your application you should consider

defining the object in XML as you can always modify properties once it is

instantiated

Once youve defined your Drawable in XML save the file in

the resdrawable directory of your project Then retrieve and instantiate the

object by calling ResourcesgetDrawable() passing it the resource ID of your XML

file (See the example below)

Any Drawable subclass that supports the inflate() method can be defined in XML

and instantiated by your application Each Drawable that supports XML inflation

utilizes specific XML attributes that help define the object properties (see the class

reference to see what these are) See the class documentation for each Drawable

subclass for information on how to define it in XML

Example

Heres some XML that defines a TransitionDrawable

lttransition xmlnsandroid=httpschemasandroidcomapkresandroidgt ltitem androiddrawable=drawableimage_expandgt ltitem androiddrawable=drawableimage_collapsegt

lttransitiongt

With this XML saved in the file resdrawableexpand_collapsexml the following

code will instantiate the TransitionDrawable and set it as the content of an

ImageView

Resources res = mContextgetResources() TransitionDrawable transition = (TransitionDrawable)

resgetDrawable(Rdrawableexpand_collapse)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 7

ImageView image = (ImageView) findViewById(Ridtoggle_image)

imagesetImageDrawable(transition)

Then this transition can be run forward (for 1 second) with

transitionstartTransition(1000)

Canvas class

The Canvas class holds the draw calls To draw something you need 4 basic

components A Bitmap to hold the pixels a Canvas to host the draw calls (writing

into the bitmap) a drawing primitive (eg Rect Path text Bitmap) and a paint (to

describe the colors and styles for the drawing)

Public Constructors

Canvas() Construct an empty raster canvas

Canvas(Bitmap bitmap) Construct a canvas with the specified bitmap to draw into

Public Methods

void drawArc(RectF oval float startAngle float sweepAngle boolean useCenter Paint paint)

Draw the specified arc which will be scaled to fit inside the specified

oval

void drawBitmap(Bitmap bitmap float left float top Paint paint) Draw the specified bitmap with its topleft corner at (xy) using the

specified paint transformed by the current matrix

void drawCircle(float cx float cy float radius Paint paint) Draw the specified circle using the specified paint

void drawColor(int color) Fill the entire canvas bitmap (restricted to the current clip) with the specified color using srcover porterduff mode

void drawLine(float startX float startY float stopX float stopY Paint paint)

Draw a line segment with the specified start and stop xy coordinates using the specified paint

void drawLines(float[] pts Paint paint)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 8

void drawLines(float[] pts int offset int count Paint paint)

Draw a series of lines

void drawOval(RectF oval Paint paint)

Draw the specified oval using the specified paint

void drawPaint(Paint paint)

Fill the entire canvas bitmap (restricted to the current clip) with the specified paint

void drawPicture(Picture picture) Save the canvas state draw the picture and restore the canvas state

void drawPicture(Picture picture Rect dst) Draw the picture stretched to fit into the dst rectangle

void drawPoint(float x float y Paint paint) Helper for drawPoints() for drawing a single point

void drawPoints(float[] pts int offset int count Paint paint) Draw a series of points

void drawPoints(float[] pts Paint paint) Helper for drawPoints() that assumes you want to draw the entire

array

void drawPosText(char[] text int index int count float[] pos Paint paint)

Draw the text in the array with each characters origin specified by the pos array

void drawPosText(String text float[] pos Paint paint) Draw the text in the array with each characters origin specified by the pos array

void drawRGB(int r int g int b) Fill the entire canvas bitmap (restricted to the current clip) with the

specified RGB color using srcover porterduff mode

void drawRect(float left float top float right float bottom Paint paint)

Draw the specified Rect using the specified paint

void drawRect(RectF rect Paint paint)

Draw the specified Rect using the specified paint

void drawRect(Rect r Paint paint)

Draw the specified Rect using the specified Paint

void drawRoundRect(RectF rect float rx float ry Paint paint)

Draw the specified round-rect using the specified paint

void drawText(String text float x float y Paint paint)

Draw the text with origin at (xy) using the specified paint

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 9

void drawText(CharSequence text int start int end float x float

y Paint paint) Draw the specified range of text specified by startend with its origin at (xy) in the specified Paint

void drawText(char[] text int index int count float x float y Paint paint) Draw the text with origin at (xy) using the specified paint

void drawText(String text int start int end float x float y Paint paint) Draw the text with origin at (xy) using the specified paint

void drawTextOnPath(String text Path path float hOffset float vOffset Paint paint)

Draw the text with origin at (xy) using the specified paint along the specified path

void drawTextOnPath(char[] text int index int count Path path float hOffset float vOffset Paint paint)

Draw the text with origin at (xy) using the specified paint along the specified path

int getHeight() Returns the height of the current drawing layer

void getMatrix(Matrix ctm) Return in ctm the current transformation matrix

final Matrix

getMatrix() Return a new matrix with a copy of the canvas current transformation matrix

int getWidth() Returns the width of the current drawing layer

void rotate(float degrees) Preconcat the current matrix with the specified rotation

final void

rotate(float degrees float px float py) Preconcat the current matrix with the specified rotation

void scale(float sx float sy) Preconcat the current matrix with the specified scale

final

void scale(float sx float sy float px float py)

Preconcat the current matrix with the specified scale

void setBitmap(Bitmap bitmap)

Specify a bitmap for the canvas to draw into

void translate(float dx float dy)

Preconcat the current matrix with the specified translation

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 10

Paint class

The Paint class holds the style and color information about how to draw

geometries text and bitmaps

Paint Styles

public static final PaintStyle FILL

Geometry and text drawn with this style will be filled ignoring all stroke-related

settings in the paint

public static final PaintStyle FILL_AND_STROKE

Geometry and text drawn with this style will be both filled and stroked at the same time respecting the stroke-related fields on the paint This mode can give unexpected results if the geometry is oriented counter-clockwise This restriction

does not apply to either FILL or STROKE

public static final PaintStyle STROKE

Geometry and text drawn with this style will be stroked respecting the stroke-related fields on the paint

Public Constructors

Paint()

Create a new paint with default settings

Paint(int flags)

Create a new paint with the specified flags

Paint(Paint paint)

Create a new paint initialized with the attributes in the specified paint parameter

Public Methods

int getAlpha()

Helper to getColor() that just returns the colors alpha value

int getColor()

Return the paints color

ColorFilter getColorFilter()

Get the paints colorfilter (maybe be null)

boolean

getFillPath(Path src Path dst)

Applies anyall effects (patheffect stroking) to src returning

the result in dst

int getFlags()

Return the paints flags

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 11

PaintFontMetrics

getFontMetrics()

Allocates a new FontMetrics object and then calls

getFontMetrics(fm) with it returning the object

int

getFontMetricsInt(PaintFontMetricsInt fmi)

Return the fonts interline spacing given the Paints settings

for typeface textSize etc

float

getFontSpacing()

Return the recommend line spacing based on the current

typeface and text size

MaskFilter getMaskFilter()

Get the paints maskfilter object

Shader getShader()

Get the paints shader object

PaintStyle

getStyle()

Return the paints style used for controlling how primitives

geometries are interpreted (except for drawBitmap which

always assumes FILL_STYLE)

PaintAlign getTextAlign()

Return the paints Align value for drawing text

void

getTextBounds(char[] text int index int count Rect bounds)

Return in bounds (allocated by the caller) the smallest

rectangle that encloses all of the characters with an implied

origin at (00)

void

getTextBounds(String text int start int end Rect bounds)

Return in bounds (allocated by the caller) the smallest

rectangle that encloses all of the characters with an implied

origin at (00)

void

getTextPath(String text int start int end float x float y Path

path)

Return the path (outline) for the specified text

void

getTextPath(char[] text int index int count float x float y

Path path)

Return the path (outline) for the specified text

float getTextScaleX()

Return the paints horizontal scale factor for text

float getTextSize()

Return the paints text size

int getTextWidths(String text float[] widths)

Return the advance widths for the characters in the string

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 12

int

getTextWidths(CharSequence text int start int end float[]

widths)

Return the advance widths for the characters in the string

int getTextWidths(String text int start int end float[] widths)

Return the advance widths for the characters in the string

int getTextWidths(char[] text int index int count float[] widths)

Return the advance widths for the characters in the string

Typeface getTypeface()

Get the paints typeface object

final boolean

isAntiAlias()

Helper for getFlags() returning true if ANTI_ALIAS_FLAG bit is

set AntiAliasing smooths out the edges of what is being

drawn but is has no impact on the interior of the shape

final boolean

isStrikeThruText()

Helper for getFlags() returning true if

STRIKE_THRU_TEXT_FLAG bit is set

final boolean

isSubpixelText()

Helper for getFlags() returning true if SUBPIXEL_TEXT_FLAG

bit is set

final boolean

isUnderlineText()

Helper for getFlags() returning true if

UNDERLINE_TEXT_FLAG bit is set

float measureText(String text)

Return the width of the text

float measureText(CharSequence text int start int end)

Return the width of the text

float measureText(String text int start int end)

Return the width of the text

float measureText(char[] text int index int count)

Return the width of the text

void reset()

Restores the paint to its default settings

void set(Paint src)

Copy the fields from src into this paint

void

setARGB(int a int r int g int b)

Helper to setColor() that takes argb and constructs the

color int

void setAlpha(int a)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 13

Helper to setColor() that only assigns the colors alpha value

leaving its rgb values unchanged

void

setAntiAlias(boolean aa)

Helper for setFlags() setting or clearing the ANTI_ALIAS_FLAG

bit AntiAliasing smooths out the edges of what is being drawn

but is has no impact on the interior of the shape

void setColor(int color)

Set the paints color

ColorFilter setColorFilter(ColorFilter filter)

Set or clear the paints colorfilter returning the parameter

void

setFakeBoldText(boolean fakeBoldText)

Helper for setFlags() setting or clearing the

FAKE_BOLD_TEXT_FLAG bit

void setFlags(int flags)

Set the paints flags

PathEffect setPathEffect(PathEffect effect)

Set or clear the patheffect object

Shader setShader(Shader shader)

Set or clear the shader object

void

setShadowLayer(float radius float dx float dy int color)

This draws a shadow layer below the main layer with the

specified offset and color and blur radius

void

setStrikeThruText(boolean strikeThruText)

Helper for setFlags() setting or clearing the

STRIKE_THRU_TEXT_FLAG bit

void

setStyle(PaintStyle style)

Set the paints style used for controlling how primitives

geometries are interpreted (except for drawBitmap which

always assumes Fill)

void

setSubpixelText(boolean subpixelText)

Helper for setFlags() setting or clearing the

SUBPIXEL_TEXT_FLAG bit

void setTextAlign(PaintAlign align)

Set the paints text alignment

void setTextSize(float textSize)

Set the paints text size

void setTextSkewX(float skewX)

Set the paints horizontal skew factor for text

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 14

Typeface setTypeface(Typeface typeface)

Set or clear the typeface object

void

setUnderlineText(boolean underlineText)

Helper for setFlags() setting or clearing the

UNDERLINE_TEXT_FLAG bit

Types of Gradient

1 Linear Gradient

public LinearGradient (float x0 float y0 float x1 float y1 int[] colors float[]

positions ShaderTileMode tile)

Create a shader that draws a linear gradient along a line

Parameters

x0 The x-coordinate for the start of the gradient line

y0 The y-coordinate for the start of the gradient line

x1 The x-coordinate for the end of the gradient line

y1 The y-coordinate for the end of the gradient line

colors The colors to be distributed along the gradient line

positions

May be null The relative positions [01] of each corresponding color in

the colors array If this is null the the colors are distributed evenly

along the gradient line

tile The Shader tiling mode

2 Sweep Gradient

public SweepGradient (float cx float cy int[] colors float[] positions)

A subclass of Shader that draws a sweep gradient around a center point

Parameters

cx The x-coordinate of the center

cy The y-coordinate of the center

colors The colors to be distributed between around the center There must be

at least 2 colors in the array

positions

May be NULL The relative position of each corresponding color in the

colors array beginning with 0 and ending with 10 If the values are not

monotonic the drawing may produce unexpected results If positions is

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 15

NULL then the colors are automatically spaced evenly

3 Radial Gradient

public RadialGradient (float x float y float radius int[] colors float[] positions

ShaderTileMode tile)

Create a shader that draws a radial gradient given the center and radius

Parameters

x The x-coordinate of the center of the radius

y The y-coordinate of the center of the radius

radius Must be positive The radius of the circle for this gradient

colors The colors to be distributed between the center and edge of the circle

positions

May be NULL The relative position of each corresponding color in the

colors array If this is NULL the the colors are distributed evenly

between the center and edge of the circle

tile The Shader tiling mode

Shader Class

Shader is the based class for objects that return horizontal spans of colors during

drawing A subclass of Shader is installed in a Paint calling

paintsetShader(shader) After that any object (other than a bitmap) that is drawn

with that paint will get its color(s) from the shader

ShaderTileMode CLAMP replicate the edge color if the shader draws

outside of its original bounds

ShaderTileMode MIRROR repeat the shaders image horizontally and

vertically alternating mirror images so that adjacent images always seam

ShaderTileMode REPEAT repeat the shaders image horizontally and

vertically

Color

The Color class defines methods for creating and converting color ints Colors are

represented as packed ints made up of 4 bytes alpha red green blue The

values are unpremultiplied meaning any transparency is stored solely in the

alpha component and not in the color components The components are stored as

follows (alpha ltlt 24) | (red ltlt 16) | (green ltlt 8) | blue Each component ranges

between 0255 with 0 meaning no contribution for that component and 255

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 16

meaning 100 contribution Thus opaque-black would be 0xFF000000 (100

opaque but no contributions from red green or blue) and opaque-white would be

0xFFFFFFFF

Constant

int BLACK int LTGRAY

int BLUE int MAGENTA

int CYAN int RED

int DKGRAY int TRANSPARENT

int GRAY int WHITE

int GREEN int YELLOW

Public Constructors

Color()

Public Methods

static int HSVToColor(float[] hsv)

Convert HSV components to an ARGB color

static int HSVToColor(int alpha float[] hsv)

Convert HSV components to an ARGB color

static void RGBToHSV(int red int green int blue float[] hsv)

Convert RGB components to HSV

static int alpha(int color)

Return the alpha component of a color int

static int argb(int alpha int red int green int blue)

Return a color-int from alpha red green blue components

static int blue(int color)

Return the blue component of a color int

static void colorToHSV(int color float[] hsv)

Convert the argb color to its HSV components

static int green(int color)

Return the green component of a color int

static int parseColor(String colorString)

Parse the color string and return the corresponding color-int

static int red(int color)

Return the red component of a color int

static int rgb(int red int green int blue)

Return a color-int from red green blue components

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 17

Working with Text

Android provide several default fonts typeface and styles Application can also use

custom fonts by including font files as application assets and loading them using

the AssetManger same as recourses

Typeface class

The Typeface class specifies the typeface and intrinsic style of a font This is used

in the paint along with optionally Paint settings like textSize textSkewX

textScaleX to specify how text appears when drawn (and measured)

Constant

int BOLD

int BOLD_ITALIC

int ITALIC

int NORMAL

Fields

public static

final Typeface DEFAULT The default NORMAL typeface object

public static

final Typeface DEFAULT_BOLD The default BOLD typeface object

public static

final Typeface MONOSPACE The NORMAL style of the default monospace typeface

public static

final Typeface SANS_SERIF The NORMAL style of the default sans serif typeface

public static

final Typeface SERIF The NORMAL style of the default serif typeface

Public Methods

static

Typeface

create(String familyName int style)

Create a typeface object given a family name and option style

information

static

Typeface

create(Typeface family int style)

Create a typeface object that best matches the specified existing typeface

and the specified Style

static

Typeface

createFromAsset(AssetManager mgr String path)

Create a new typeface from the specified font data

static

Typeface

createFromFile(String path)

Create a new typeface from the specified font file

static createFromFile(File path)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 18

Typeface Create a new typeface from the specified font file

static

Typeface

defaultFromStyle(int style)

Returns one of the default typeface objects based on the specified style

int getStyle()

Returns the typefaces intrinsic style attributes

final

boolean

isBold()

Returns true if getStyle() has the BOLD bit set

final

boolean

isItalic()

Returns true if getStyle() has the ITALIC bit set

Using Default Fonts and Typefaces

By default Android uses the Sans Serif typeface but Monospace and Serif

typefaces are also available The following code excerpt draws some antialiased text in the default typeface (Sans Serif) to a Canvas

import androidgraphicsCanvas import androidgraphicsColor import androidgraphicsPaint import androidgraphicsTypeface Paint mPaint = new Paint(PaintANTI_ALIAS_FLAG) Typeface mType mPaintsetTextSize(16) mPaintsetTypeface(null) canvasdrawText(ldquoDefault Typefacerdquo 20 20 mPaint) You can instead load a different typeface such as Monotype

Typeface mType = Typefacecreate(TypefaceMONOSPACE TypefaceNORMAL) Perhaps you would prefer italic text in which case you can simply set the style of the typeface and the font family

Typeface mType = Typefacecreate(TypefaceSERIF TypefaceITALIC)

You can set certain properties of a typeface such as antialiasing underlining and strikethrough using the setFlags() method of the Paint object

mPaintsetFlags(PaintUNDERLINE_TEXT_FLAG)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 19

Loading Custom typeface from asset

Typeface mType = TypefacecreateFromAsset(getContext()getAssets()ldquofontschess1ttfrdquo) Example ViewFontjava

package compritesh

import androidcontentContext import androidgraphicsCanvas import androidgraphicsColor import androidgraphicsPaint import androidgraphicsTypeface import androidviewView public class ViewFont extends View Context c public ViewFont(Context context) super(context) c=context protected void onDraw(Canvas canvas) Typeface mType = TypefacecreateFromAsset( cgetAssets() fontsBaroqueScriptttf) Paint p =new Paint(PaintANTI_ALIAS_FLAG) psetTypeface(mType) psetTextSize(20) canvasdrawColor(ColorBLUE) canvasdrawText(Welcome to Android canvasgetWidth()4 canvasgetHeight()3 p)

SampleCustomFontjava package compritesh import androidappActivity import androidgraphicsTypeface import androidosBundle public class SampleCustomFont extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain) setContentView(new ViewFont(this))

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 20

Working with Bitmap and Matrix Bitmap

In computer graphics a bitmap or pixmap is a type of memory organization

or image file format used to store digital images The term bitmap comes from the

computer programming terminology meaning just a map of bits a spatially mapped array of bits Now along with pixmap it commonly refers to the similar

concept of a spatially mapped array of pixels Raster images in general may be referred to as bitmaps or pixmaps whether synthetic or photographic in files or

memory In certain contexts the term bitmap implies one bit per pixel while pixmap

is used for images with multiple bits per pixel

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 21

Shape Drawable in XML

This is a generic shape defined in XML

File location

resdrawablefilenamexml

The filename is used as the resource ID

Compiled resource datatype

Resource pointer to a GradientDrawable

Resource reference

In Java Rdrawablefilename

In XML [package]drawablefilename

Syntax

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=[rectangle | oval | line | ring] gt ltcorners androidradius=integer androidtopLeftRadius=integer androidtopRightRadius=integer androidbottomLeftRadius=integer androidbottomRightRadius=integer gt ltgradient androidangle=integer androidcenterX=integer androidcenterY=integer androidcenterColor=integer androidendColor=color androidgradientRadius=integer androidstartColor=color androidtype=[linear | radial | sweep] androidusesLevel=[true | false] gt ltpadding androidleft=integer androidtop=integer androidright=integer androidbottom=integer gt ltsize androidwidth=integer androidheight=integer gt ltsolid

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 22

androidcolor=color gt ltstroke androidwidth=integer androidcolor=color androiddashWidth=integer androiddashGap=integer gt ltshapegt

Elements

ltshapegt

The shape drawable This must be the root element

Attributes

xmlnsandroid

String Required Defines the XML namespace which must be

httpschemasandroidcomapkresandroid

androidshape

Keyword Defines the type of shape Valid values are

Value Desciption

rectangle A rectangle that fills the containing View This is the default shape

oval An oval shape that fits the dimensions of the containing View

line A horizontal line that spans the width of the containing View This

shape requires the ltstrokegt element to define the width of the line

ring A ring shape

The following attributes are used only when androidshape=ring

androidinnerRadius

Dimension The radius for the inner part of the ring (the hole in the middle)

as a dimension value or dimension resource

androidinnerRadiusRatio

Float The radius for the inner part of the ring expressed as a ratio of the

rings width For instance if androidinnerRadiusRatio=5 then the inner

radius equals the rings width divided by 5 This value is overridden by

androidinnerRadius Default value is 9

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 23

androidthickness

Dimension The thickness of the ring as a dimension value or dimension

resource

androidthicknessRatio

Float The thickness of the ring expressed as a ratio of the rings width For

instance if androidthicknessRatio=2 then the thickness equals the rings

width divided by 2 This value is overridden by androidinnerRadius Default

value is 3

androiduseLevel

Boolean true if this is used as a LevelListDrawable This should normally

be false or your shape may not appear

ltcornersgt

Creates rounded corners for the shape Applies only when the shape is a

rectangle

Attributes

androidradius

Dimension The radius for all corners as a dimension value or dimension

resource This is overridden for each corner by the following attributes

androidtopLeftRadius

Dimension The radius for the top-left corner as a dimension value or

dimension resource

androidtopRightRadius

Dimension The radius for the top-right corner as a dimension value or

dimension resource

androidbottomLeftRadius

Dimension The radius for the bottom-left corner as a dimension value or

dimension resource

androidbottomRightRadius

Dimension The radius for the bottom-right corner as a dimension value or

dimension resource

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 24

Note Every corner must (initially) be provided a corner radius greater than

1 or else no corners are rounded If you want specific corners to not be rounded a work-around is to use androidradius to set a default corner

radius greater than 1 but then override each and every corner with the values you really want providing zero (0dp) where you dont want rounded

corners

ltgradientgt

Specifies a gradient color for the shape

Attributes

androidangle

Integer The angle for the gradient in degrees 0 is left to right 90 is bottom

to top It must be a multiple of 45 Default is 0

androidcenterX

Float The relative X-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterY

Float The relative Y-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterColor

Color Optional color that comes between the start and end colors as a

hexadecimal value or color resource

androidendColor

Color The ending color as a hexadecimal value or color resource

androidgradientRadius

Float The radius for the gradient Only applied when androidtype=radial

androidstartColor

Color The starting color as a hexadecimal value or color resource

androidtype

Keyword The type of gradient pattern to apply Valid values are

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 25

Value Description

linear A linear gradient This is the default

radial A radial gradient The start color is the center color

sweep A sweeping line gradient

androiduseLevel

Boolean true if this is used as a LevelListDrawable

ltpaddinggt

Padding to apply to the containing View element (this pads the position of

the View content not the shape)

Attributes

androidleft

Dimension Left padding as a dimension value or dimension resource

androidtop

Dimension Top padding as a dimension value or dimension resource

androidright

Dimension Right padding as a dimension value or dimension resource

androidbottom

Dimension Bottom padding as a dimension value or dimension resource

ltsizegt

The size of the shape

Attributes

androidheight

Dimension The height of the shape as a dimension value or dimension

resource

androidwidth

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 26

Dimension The width of the shape as a dimension value or dimension

resource

Note The shape scales to the size of the container View proportionate to the

dimensions defined here by default When you use the shape in an ImageView you can restrict scaling by setting the androidscaleType to center

ltsolidgt

A solid color to fill the shape

Attributes

androidcolor

Color The color to apply to the shape as a hexadecimal value or color

resource

ltstrokegt

A stroke line for the shape

Attributes

androidwidth

Dimension The thickness of the line as a dimension value or dimension

resource

androidcolor

Color The color of the line as a hexadecimal value or color resource

androiddashGap

Dimension The distance between line dashes as a dimension value or

dimension resource Only valid if androiddashWidth is set

androiddashWidth

Dimension The size of each dash line as a dimension value or dimension

resource Only valid if androiddashGap is set

Example

XML file saved at resdrawablegradient_boxxml

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 27

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=rectanglegt ltgradient androidstartColor=FFFF0000 androidendColor=80FF00FF androidangle=45gt ltpadding androidleft=7dp androidtop=7dp androidright=7dp androidbottom=7dp gt ltcorners androidradius=8dp gt ltshapegt

This layout XML applies the shape drawable to a View

ltTextView androidbackground=drawablegradient_box androidlayout_height=wrap_content androidlayout_width=wrap_content gt

This application code gets the shape drawable and applies it to a View

Resources res = getResources() Drawable shape = res getDrawable(Rdrawablegradient_box)

TextView tv = (TextView)findViewByID(Ridtextview) tvsetBackground(shape)

Page 4: Android graphics mca 5th

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 4

the Canvas as you left it Perform this sequence of locking and unlocking the canvas each time you want to redraw

Note On each pass you retrieve the Canvas from the SurfaceHolder the previous state of the Canvas will be retained In order to properly animate your graphics

you must re-paint the entire surface For example you can clear the previous state of the Canvas by filling in a color with drawColor() or setting a background image with drawBitmap() Otherwise you will see traces of the drawings you

previously performed

2D Graphics

Android offers a custom 2D graphics library for drawing and animating shapes

and images Theandroidgraphicsdrawable andandroidviewanimation packages

are where youll find the common classes used for drawing and animating in two-

dimensions

This document offers an introduction to drawing graphics in your Android

application Well discuss the basics of using Drawable objects to draw graphics

how to use a couple subclasses of the Drawable class and how to create

animations that either tween (move stretch rotate) a single graphic or animate a

series of graphics (like a roll of film)

Drawables

A Drawable is a general abstraction for something that can be drawn Youll

discover that the Drawable class extends to define a variety of specific kinds of

drawable graphics

including BitmapDrawable ShapeDrawable PictureDrawableLayerDrawable and

several more Of course you can also extend these to define your own custom

Drawable objects that behave in unique ways

There are three ways to define and instantiate a Drawable using an image saved

in your project resources using an XML file that defines the Drawable properties

or using the normal class constructors Below well discuss each the first two

techniques (using constructors is nothing new for an experienced developer)

Creating from resource images

A simple way to add graphics to your application is by referencing an image file

from your project resources Supported file types are PNG (preferred) JPG

(acceptable) and GIF (discouraged) This technique would obviously be preferred

for application icons logos or other graphics such as those used in a game

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 5

To use an image resource just add your file to the resdrawable directory of your

project From there you can reference it from your code or your XML layout

Either way it is referred using a resource ID which is the file name without the

file type extension (Eg my_imagepng is referenced as my_image)

Example code

The following code snippet demonstrates how to build an ImageView that uses an

image from drawable resources and add it to the layout

LinearLayout mLinearLayout

protected void onCreate(Bundle savedInstanceState)

superonCreate(savedInstanceState) Create a LinearLayout in which to add the ImageView

mLinearLayout = new LinearLayout(this) Instantiate an ImageView and define its properties

ImageView i = new ImageView(this) isetImageResource(Rdrawablemy_image)

isetAdjustViewBounds(true) set the ImageView bounds to match the Drawables dimensions isetLayoutParams(new

GalleryLayoutParams(LayoutParamsWRAP_CONTENT LayoutParamsWRAP_CONTENT))

Add the ImageView to the layout and set the layout as the content view mLinearLayoutaddView(i)

setContentView(mLinearLayout)

In other cases you may want to handle your image resource as a Drawable object

To do so create a Drawable from the resource like so

Resources res = mContextgetResources()

Drawable myImage = resgetDrawable(Rdrawablemy_image)

Example XML

The XML snippet below shows how to add a resource Drawable to an ImageView in

the XML layout (with some red tint just for fun)

ltImageView androidlayout_width=wrap_content

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 6

androidlayout_height=wrap_content androidtint=55ff0000

androidsrc=drawablemy_imagegt

Creating from resource XML

By now you should be familiar with Androids principles of developing a User

Interface Hence you understand the power and flexibility inherent in defining

objects in XML This philosophy caries over from Views to Drawables If there is a

Drawable object that youd like to create which is not initially dependent on

variables defined by your application code or user interaction then defining the

Drawable in XML is a good option Even if you expect your Drawable to change its

properties during the users experience with your application you should consider

defining the object in XML as you can always modify properties once it is

instantiated

Once youve defined your Drawable in XML save the file in

the resdrawable directory of your project Then retrieve and instantiate the

object by calling ResourcesgetDrawable() passing it the resource ID of your XML

file (See the example below)

Any Drawable subclass that supports the inflate() method can be defined in XML

and instantiated by your application Each Drawable that supports XML inflation

utilizes specific XML attributes that help define the object properties (see the class

reference to see what these are) See the class documentation for each Drawable

subclass for information on how to define it in XML

Example

Heres some XML that defines a TransitionDrawable

lttransition xmlnsandroid=httpschemasandroidcomapkresandroidgt ltitem androiddrawable=drawableimage_expandgt ltitem androiddrawable=drawableimage_collapsegt

lttransitiongt

With this XML saved in the file resdrawableexpand_collapsexml the following

code will instantiate the TransitionDrawable and set it as the content of an

ImageView

Resources res = mContextgetResources() TransitionDrawable transition = (TransitionDrawable)

resgetDrawable(Rdrawableexpand_collapse)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 7

ImageView image = (ImageView) findViewById(Ridtoggle_image)

imagesetImageDrawable(transition)

Then this transition can be run forward (for 1 second) with

transitionstartTransition(1000)

Canvas class

The Canvas class holds the draw calls To draw something you need 4 basic

components A Bitmap to hold the pixels a Canvas to host the draw calls (writing

into the bitmap) a drawing primitive (eg Rect Path text Bitmap) and a paint (to

describe the colors and styles for the drawing)

Public Constructors

Canvas() Construct an empty raster canvas

Canvas(Bitmap bitmap) Construct a canvas with the specified bitmap to draw into

Public Methods

void drawArc(RectF oval float startAngle float sweepAngle boolean useCenter Paint paint)

Draw the specified arc which will be scaled to fit inside the specified

oval

void drawBitmap(Bitmap bitmap float left float top Paint paint) Draw the specified bitmap with its topleft corner at (xy) using the

specified paint transformed by the current matrix

void drawCircle(float cx float cy float radius Paint paint) Draw the specified circle using the specified paint

void drawColor(int color) Fill the entire canvas bitmap (restricted to the current clip) with the specified color using srcover porterduff mode

void drawLine(float startX float startY float stopX float stopY Paint paint)

Draw a line segment with the specified start and stop xy coordinates using the specified paint

void drawLines(float[] pts Paint paint)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 8

void drawLines(float[] pts int offset int count Paint paint)

Draw a series of lines

void drawOval(RectF oval Paint paint)

Draw the specified oval using the specified paint

void drawPaint(Paint paint)

Fill the entire canvas bitmap (restricted to the current clip) with the specified paint

void drawPicture(Picture picture) Save the canvas state draw the picture and restore the canvas state

void drawPicture(Picture picture Rect dst) Draw the picture stretched to fit into the dst rectangle

void drawPoint(float x float y Paint paint) Helper for drawPoints() for drawing a single point

void drawPoints(float[] pts int offset int count Paint paint) Draw a series of points

void drawPoints(float[] pts Paint paint) Helper for drawPoints() that assumes you want to draw the entire

array

void drawPosText(char[] text int index int count float[] pos Paint paint)

Draw the text in the array with each characters origin specified by the pos array

void drawPosText(String text float[] pos Paint paint) Draw the text in the array with each characters origin specified by the pos array

void drawRGB(int r int g int b) Fill the entire canvas bitmap (restricted to the current clip) with the

specified RGB color using srcover porterduff mode

void drawRect(float left float top float right float bottom Paint paint)

Draw the specified Rect using the specified paint

void drawRect(RectF rect Paint paint)

Draw the specified Rect using the specified paint

void drawRect(Rect r Paint paint)

Draw the specified Rect using the specified Paint

void drawRoundRect(RectF rect float rx float ry Paint paint)

Draw the specified round-rect using the specified paint

void drawText(String text float x float y Paint paint)

Draw the text with origin at (xy) using the specified paint

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 9

void drawText(CharSequence text int start int end float x float

y Paint paint) Draw the specified range of text specified by startend with its origin at (xy) in the specified Paint

void drawText(char[] text int index int count float x float y Paint paint) Draw the text with origin at (xy) using the specified paint

void drawText(String text int start int end float x float y Paint paint) Draw the text with origin at (xy) using the specified paint

void drawTextOnPath(String text Path path float hOffset float vOffset Paint paint)

Draw the text with origin at (xy) using the specified paint along the specified path

void drawTextOnPath(char[] text int index int count Path path float hOffset float vOffset Paint paint)

Draw the text with origin at (xy) using the specified paint along the specified path

int getHeight() Returns the height of the current drawing layer

void getMatrix(Matrix ctm) Return in ctm the current transformation matrix

final Matrix

getMatrix() Return a new matrix with a copy of the canvas current transformation matrix

int getWidth() Returns the width of the current drawing layer

void rotate(float degrees) Preconcat the current matrix with the specified rotation

final void

rotate(float degrees float px float py) Preconcat the current matrix with the specified rotation

void scale(float sx float sy) Preconcat the current matrix with the specified scale

final

void scale(float sx float sy float px float py)

Preconcat the current matrix with the specified scale

void setBitmap(Bitmap bitmap)

Specify a bitmap for the canvas to draw into

void translate(float dx float dy)

Preconcat the current matrix with the specified translation

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 10

Paint class

The Paint class holds the style and color information about how to draw

geometries text and bitmaps

Paint Styles

public static final PaintStyle FILL

Geometry and text drawn with this style will be filled ignoring all stroke-related

settings in the paint

public static final PaintStyle FILL_AND_STROKE

Geometry and text drawn with this style will be both filled and stroked at the same time respecting the stroke-related fields on the paint This mode can give unexpected results if the geometry is oriented counter-clockwise This restriction

does not apply to either FILL or STROKE

public static final PaintStyle STROKE

Geometry and text drawn with this style will be stroked respecting the stroke-related fields on the paint

Public Constructors

Paint()

Create a new paint with default settings

Paint(int flags)

Create a new paint with the specified flags

Paint(Paint paint)

Create a new paint initialized with the attributes in the specified paint parameter

Public Methods

int getAlpha()

Helper to getColor() that just returns the colors alpha value

int getColor()

Return the paints color

ColorFilter getColorFilter()

Get the paints colorfilter (maybe be null)

boolean

getFillPath(Path src Path dst)

Applies anyall effects (patheffect stroking) to src returning

the result in dst

int getFlags()

Return the paints flags

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 11

PaintFontMetrics

getFontMetrics()

Allocates a new FontMetrics object and then calls

getFontMetrics(fm) with it returning the object

int

getFontMetricsInt(PaintFontMetricsInt fmi)

Return the fonts interline spacing given the Paints settings

for typeface textSize etc

float

getFontSpacing()

Return the recommend line spacing based on the current

typeface and text size

MaskFilter getMaskFilter()

Get the paints maskfilter object

Shader getShader()

Get the paints shader object

PaintStyle

getStyle()

Return the paints style used for controlling how primitives

geometries are interpreted (except for drawBitmap which

always assumes FILL_STYLE)

PaintAlign getTextAlign()

Return the paints Align value for drawing text

void

getTextBounds(char[] text int index int count Rect bounds)

Return in bounds (allocated by the caller) the smallest

rectangle that encloses all of the characters with an implied

origin at (00)

void

getTextBounds(String text int start int end Rect bounds)

Return in bounds (allocated by the caller) the smallest

rectangle that encloses all of the characters with an implied

origin at (00)

void

getTextPath(String text int start int end float x float y Path

path)

Return the path (outline) for the specified text

void

getTextPath(char[] text int index int count float x float y

Path path)

Return the path (outline) for the specified text

float getTextScaleX()

Return the paints horizontal scale factor for text

float getTextSize()

Return the paints text size

int getTextWidths(String text float[] widths)

Return the advance widths for the characters in the string

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 12

int

getTextWidths(CharSequence text int start int end float[]

widths)

Return the advance widths for the characters in the string

int getTextWidths(String text int start int end float[] widths)

Return the advance widths for the characters in the string

int getTextWidths(char[] text int index int count float[] widths)

Return the advance widths for the characters in the string

Typeface getTypeface()

Get the paints typeface object

final boolean

isAntiAlias()

Helper for getFlags() returning true if ANTI_ALIAS_FLAG bit is

set AntiAliasing smooths out the edges of what is being

drawn but is has no impact on the interior of the shape

final boolean

isStrikeThruText()

Helper for getFlags() returning true if

STRIKE_THRU_TEXT_FLAG bit is set

final boolean

isSubpixelText()

Helper for getFlags() returning true if SUBPIXEL_TEXT_FLAG

bit is set

final boolean

isUnderlineText()

Helper for getFlags() returning true if

UNDERLINE_TEXT_FLAG bit is set

float measureText(String text)

Return the width of the text

float measureText(CharSequence text int start int end)

Return the width of the text

float measureText(String text int start int end)

Return the width of the text

float measureText(char[] text int index int count)

Return the width of the text

void reset()

Restores the paint to its default settings

void set(Paint src)

Copy the fields from src into this paint

void

setARGB(int a int r int g int b)

Helper to setColor() that takes argb and constructs the

color int

void setAlpha(int a)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 13

Helper to setColor() that only assigns the colors alpha value

leaving its rgb values unchanged

void

setAntiAlias(boolean aa)

Helper for setFlags() setting or clearing the ANTI_ALIAS_FLAG

bit AntiAliasing smooths out the edges of what is being drawn

but is has no impact on the interior of the shape

void setColor(int color)

Set the paints color

ColorFilter setColorFilter(ColorFilter filter)

Set or clear the paints colorfilter returning the parameter

void

setFakeBoldText(boolean fakeBoldText)

Helper for setFlags() setting or clearing the

FAKE_BOLD_TEXT_FLAG bit

void setFlags(int flags)

Set the paints flags

PathEffect setPathEffect(PathEffect effect)

Set or clear the patheffect object

Shader setShader(Shader shader)

Set or clear the shader object

void

setShadowLayer(float radius float dx float dy int color)

This draws a shadow layer below the main layer with the

specified offset and color and blur radius

void

setStrikeThruText(boolean strikeThruText)

Helper for setFlags() setting or clearing the

STRIKE_THRU_TEXT_FLAG bit

void

setStyle(PaintStyle style)

Set the paints style used for controlling how primitives

geometries are interpreted (except for drawBitmap which

always assumes Fill)

void

setSubpixelText(boolean subpixelText)

Helper for setFlags() setting or clearing the

SUBPIXEL_TEXT_FLAG bit

void setTextAlign(PaintAlign align)

Set the paints text alignment

void setTextSize(float textSize)

Set the paints text size

void setTextSkewX(float skewX)

Set the paints horizontal skew factor for text

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 14

Typeface setTypeface(Typeface typeface)

Set or clear the typeface object

void

setUnderlineText(boolean underlineText)

Helper for setFlags() setting or clearing the

UNDERLINE_TEXT_FLAG bit

Types of Gradient

1 Linear Gradient

public LinearGradient (float x0 float y0 float x1 float y1 int[] colors float[]

positions ShaderTileMode tile)

Create a shader that draws a linear gradient along a line

Parameters

x0 The x-coordinate for the start of the gradient line

y0 The y-coordinate for the start of the gradient line

x1 The x-coordinate for the end of the gradient line

y1 The y-coordinate for the end of the gradient line

colors The colors to be distributed along the gradient line

positions

May be null The relative positions [01] of each corresponding color in

the colors array If this is null the the colors are distributed evenly

along the gradient line

tile The Shader tiling mode

2 Sweep Gradient

public SweepGradient (float cx float cy int[] colors float[] positions)

A subclass of Shader that draws a sweep gradient around a center point

Parameters

cx The x-coordinate of the center

cy The y-coordinate of the center

colors The colors to be distributed between around the center There must be

at least 2 colors in the array

positions

May be NULL The relative position of each corresponding color in the

colors array beginning with 0 and ending with 10 If the values are not

monotonic the drawing may produce unexpected results If positions is

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 15

NULL then the colors are automatically spaced evenly

3 Radial Gradient

public RadialGradient (float x float y float radius int[] colors float[] positions

ShaderTileMode tile)

Create a shader that draws a radial gradient given the center and radius

Parameters

x The x-coordinate of the center of the radius

y The y-coordinate of the center of the radius

radius Must be positive The radius of the circle for this gradient

colors The colors to be distributed between the center and edge of the circle

positions

May be NULL The relative position of each corresponding color in the

colors array If this is NULL the the colors are distributed evenly

between the center and edge of the circle

tile The Shader tiling mode

Shader Class

Shader is the based class for objects that return horizontal spans of colors during

drawing A subclass of Shader is installed in a Paint calling

paintsetShader(shader) After that any object (other than a bitmap) that is drawn

with that paint will get its color(s) from the shader

ShaderTileMode CLAMP replicate the edge color if the shader draws

outside of its original bounds

ShaderTileMode MIRROR repeat the shaders image horizontally and

vertically alternating mirror images so that adjacent images always seam

ShaderTileMode REPEAT repeat the shaders image horizontally and

vertically

Color

The Color class defines methods for creating and converting color ints Colors are

represented as packed ints made up of 4 bytes alpha red green blue The

values are unpremultiplied meaning any transparency is stored solely in the

alpha component and not in the color components The components are stored as

follows (alpha ltlt 24) | (red ltlt 16) | (green ltlt 8) | blue Each component ranges

between 0255 with 0 meaning no contribution for that component and 255

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 16

meaning 100 contribution Thus opaque-black would be 0xFF000000 (100

opaque but no contributions from red green or blue) and opaque-white would be

0xFFFFFFFF

Constant

int BLACK int LTGRAY

int BLUE int MAGENTA

int CYAN int RED

int DKGRAY int TRANSPARENT

int GRAY int WHITE

int GREEN int YELLOW

Public Constructors

Color()

Public Methods

static int HSVToColor(float[] hsv)

Convert HSV components to an ARGB color

static int HSVToColor(int alpha float[] hsv)

Convert HSV components to an ARGB color

static void RGBToHSV(int red int green int blue float[] hsv)

Convert RGB components to HSV

static int alpha(int color)

Return the alpha component of a color int

static int argb(int alpha int red int green int blue)

Return a color-int from alpha red green blue components

static int blue(int color)

Return the blue component of a color int

static void colorToHSV(int color float[] hsv)

Convert the argb color to its HSV components

static int green(int color)

Return the green component of a color int

static int parseColor(String colorString)

Parse the color string and return the corresponding color-int

static int red(int color)

Return the red component of a color int

static int rgb(int red int green int blue)

Return a color-int from red green blue components

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 17

Working with Text

Android provide several default fonts typeface and styles Application can also use

custom fonts by including font files as application assets and loading them using

the AssetManger same as recourses

Typeface class

The Typeface class specifies the typeface and intrinsic style of a font This is used

in the paint along with optionally Paint settings like textSize textSkewX

textScaleX to specify how text appears when drawn (and measured)

Constant

int BOLD

int BOLD_ITALIC

int ITALIC

int NORMAL

Fields

public static

final Typeface DEFAULT The default NORMAL typeface object

public static

final Typeface DEFAULT_BOLD The default BOLD typeface object

public static

final Typeface MONOSPACE The NORMAL style of the default monospace typeface

public static

final Typeface SANS_SERIF The NORMAL style of the default sans serif typeface

public static

final Typeface SERIF The NORMAL style of the default serif typeface

Public Methods

static

Typeface

create(String familyName int style)

Create a typeface object given a family name and option style

information

static

Typeface

create(Typeface family int style)

Create a typeface object that best matches the specified existing typeface

and the specified Style

static

Typeface

createFromAsset(AssetManager mgr String path)

Create a new typeface from the specified font data

static

Typeface

createFromFile(String path)

Create a new typeface from the specified font file

static createFromFile(File path)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 18

Typeface Create a new typeface from the specified font file

static

Typeface

defaultFromStyle(int style)

Returns one of the default typeface objects based on the specified style

int getStyle()

Returns the typefaces intrinsic style attributes

final

boolean

isBold()

Returns true if getStyle() has the BOLD bit set

final

boolean

isItalic()

Returns true if getStyle() has the ITALIC bit set

Using Default Fonts and Typefaces

By default Android uses the Sans Serif typeface but Monospace and Serif

typefaces are also available The following code excerpt draws some antialiased text in the default typeface (Sans Serif) to a Canvas

import androidgraphicsCanvas import androidgraphicsColor import androidgraphicsPaint import androidgraphicsTypeface Paint mPaint = new Paint(PaintANTI_ALIAS_FLAG) Typeface mType mPaintsetTextSize(16) mPaintsetTypeface(null) canvasdrawText(ldquoDefault Typefacerdquo 20 20 mPaint) You can instead load a different typeface such as Monotype

Typeface mType = Typefacecreate(TypefaceMONOSPACE TypefaceNORMAL) Perhaps you would prefer italic text in which case you can simply set the style of the typeface and the font family

Typeface mType = Typefacecreate(TypefaceSERIF TypefaceITALIC)

You can set certain properties of a typeface such as antialiasing underlining and strikethrough using the setFlags() method of the Paint object

mPaintsetFlags(PaintUNDERLINE_TEXT_FLAG)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 19

Loading Custom typeface from asset

Typeface mType = TypefacecreateFromAsset(getContext()getAssets()ldquofontschess1ttfrdquo) Example ViewFontjava

package compritesh

import androidcontentContext import androidgraphicsCanvas import androidgraphicsColor import androidgraphicsPaint import androidgraphicsTypeface import androidviewView public class ViewFont extends View Context c public ViewFont(Context context) super(context) c=context protected void onDraw(Canvas canvas) Typeface mType = TypefacecreateFromAsset( cgetAssets() fontsBaroqueScriptttf) Paint p =new Paint(PaintANTI_ALIAS_FLAG) psetTypeface(mType) psetTextSize(20) canvasdrawColor(ColorBLUE) canvasdrawText(Welcome to Android canvasgetWidth()4 canvasgetHeight()3 p)

SampleCustomFontjava package compritesh import androidappActivity import androidgraphicsTypeface import androidosBundle public class SampleCustomFont extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain) setContentView(new ViewFont(this))

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 20

Working with Bitmap and Matrix Bitmap

In computer graphics a bitmap or pixmap is a type of memory organization

or image file format used to store digital images The term bitmap comes from the

computer programming terminology meaning just a map of bits a spatially mapped array of bits Now along with pixmap it commonly refers to the similar

concept of a spatially mapped array of pixels Raster images in general may be referred to as bitmaps or pixmaps whether synthetic or photographic in files or

memory In certain contexts the term bitmap implies one bit per pixel while pixmap

is used for images with multiple bits per pixel

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 21

Shape Drawable in XML

This is a generic shape defined in XML

File location

resdrawablefilenamexml

The filename is used as the resource ID

Compiled resource datatype

Resource pointer to a GradientDrawable

Resource reference

In Java Rdrawablefilename

In XML [package]drawablefilename

Syntax

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=[rectangle | oval | line | ring] gt ltcorners androidradius=integer androidtopLeftRadius=integer androidtopRightRadius=integer androidbottomLeftRadius=integer androidbottomRightRadius=integer gt ltgradient androidangle=integer androidcenterX=integer androidcenterY=integer androidcenterColor=integer androidendColor=color androidgradientRadius=integer androidstartColor=color androidtype=[linear | radial | sweep] androidusesLevel=[true | false] gt ltpadding androidleft=integer androidtop=integer androidright=integer androidbottom=integer gt ltsize androidwidth=integer androidheight=integer gt ltsolid

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 22

androidcolor=color gt ltstroke androidwidth=integer androidcolor=color androiddashWidth=integer androiddashGap=integer gt ltshapegt

Elements

ltshapegt

The shape drawable This must be the root element

Attributes

xmlnsandroid

String Required Defines the XML namespace which must be

httpschemasandroidcomapkresandroid

androidshape

Keyword Defines the type of shape Valid values are

Value Desciption

rectangle A rectangle that fills the containing View This is the default shape

oval An oval shape that fits the dimensions of the containing View

line A horizontal line that spans the width of the containing View This

shape requires the ltstrokegt element to define the width of the line

ring A ring shape

The following attributes are used only when androidshape=ring

androidinnerRadius

Dimension The radius for the inner part of the ring (the hole in the middle)

as a dimension value or dimension resource

androidinnerRadiusRatio

Float The radius for the inner part of the ring expressed as a ratio of the

rings width For instance if androidinnerRadiusRatio=5 then the inner

radius equals the rings width divided by 5 This value is overridden by

androidinnerRadius Default value is 9

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 23

androidthickness

Dimension The thickness of the ring as a dimension value or dimension

resource

androidthicknessRatio

Float The thickness of the ring expressed as a ratio of the rings width For

instance if androidthicknessRatio=2 then the thickness equals the rings

width divided by 2 This value is overridden by androidinnerRadius Default

value is 3

androiduseLevel

Boolean true if this is used as a LevelListDrawable This should normally

be false or your shape may not appear

ltcornersgt

Creates rounded corners for the shape Applies only when the shape is a

rectangle

Attributes

androidradius

Dimension The radius for all corners as a dimension value or dimension

resource This is overridden for each corner by the following attributes

androidtopLeftRadius

Dimension The radius for the top-left corner as a dimension value or

dimension resource

androidtopRightRadius

Dimension The radius for the top-right corner as a dimension value or

dimension resource

androidbottomLeftRadius

Dimension The radius for the bottom-left corner as a dimension value or

dimension resource

androidbottomRightRadius

Dimension The radius for the bottom-right corner as a dimension value or

dimension resource

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 24

Note Every corner must (initially) be provided a corner radius greater than

1 or else no corners are rounded If you want specific corners to not be rounded a work-around is to use androidradius to set a default corner

radius greater than 1 but then override each and every corner with the values you really want providing zero (0dp) where you dont want rounded

corners

ltgradientgt

Specifies a gradient color for the shape

Attributes

androidangle

Integer The angle for the gradient in degrees 0 is left to right 90 is bottom

to top It must be a multiple of 45 Default is 0

androidcenterX

Float The relative X-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterY

Float The relative Y-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterColor

Color Optional color that comes between the start and end colors as a

hexadecimal value or color resource

androidendColor

Color The ending color as a hexadecimal value or color resource

androidgradientRadius

Float The radius for the gradient Only applied when androidtype=radial

androidstartColor

Color The starting color as a hexadecimal value or color resource

androidtype

Keyword The type of gradient pattern to apply Valid values are

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 25

Value Description

linear A linear gradient This is the default

radial A radial gradient The start color is the center color

sweep A sweeping line gradient

androiduseLevel

Boolean true if this is used as a LevelListDrawable

ltpaddinggt

Padding to apply to the containing View element (this pads the position of

the View content not the shape)

Attributes

androidleft

Dimension Left padding as a dimension value or dimension resource

androidtop

Dimension Top padding as a dimension value or dimension resource

androidright

Dimension Right padding as a dimension value or dimension resource

androidbottom

Dimension Bottom padding as a dimension value or dimension resource

ltsizegt

The size of the shape

Attributes

androidheight

Dimension The height of the shape as a dimension value or dimension

resource

androidwidth

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 26

Dimension The width of the shape as a dimension value or dimension

resource

Note The shape scales to the size of the container View proportionate to the

dimensions defined here by default When you use the shape in an ImageView you can restrict scaling by setting the androidscaleType to center

ltsolidgt

A solid color to fill the shape

Attributes

androidcolor

Color The color to apply to the shape as a hexadecimal value or color

resource

ltstrokegt

A stroke line for the shape

Attributes

androidwidth

Dimension The thickness of the line as a dimension value or dimension

resource

androidcolor

Color The color of the line as a hexadecimal value or color resource

androiddashGap

Dimension The distance between line dashes as a dimension value or

dimension resource Only valid if androiddashWidth is set

androiddashWidth

Dimension The size of each dash line as a dimension value or dimension

resource Only valid if androiddashGap is set

Example

XML file saved at resdrawablegradient_boxxml

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 27

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=rectanglegt ltgradient androidstartColor=FFFF0000 androidendColor=80FF00FF androidangle=45gt ltpadding androidleft=7dp androidtop=7dp androidright=7dp androidbottom=7dp gt ltcorners androidradius=8dp gt ltshapegt

This layout XML applies the shape drawable to a View

ltTextView androidbackground=drawablegradient_box androidlayout_height=wrap_content androidlayout_width=wrap_content gt

This application code gets the shape drawable and applies it to a View

Resources res = getResources() Drawable shape = res getDrawable(Rdrawablegradient_box)

TextView tv = (TextView)findViewByID(Ridtextview) tvsetBackground(shape)

Page 5: Android graphics mca 5th

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 5

To use an image resource just add your file to the resdrawable directory of your

project From there you can reference it from your code or your XML layout

Either way it is referred using a resource ID which is the file name without the

file type extension (Eg my_imagepng is referenced as my_image)

Example code

The following code snippet demonstrates how to build an ImageView that uses an

image from drawable resources and add it to the layout

LinearLayout mLinearLayout

protected void onCreate(Bundle savedInstanceState)

superonCreate(savedInstanceState) Create a LinearLayout in which to add the ImageView

mLinearLayout = new LinearLayout(this) Instantiate an ImageView and define its properties

ImageView i = new ImageView(this) isetImageResource(Rdrawablemy_image)

isetAdjustViewBounds(true) set the ImageView bounds to match the Drawables dimensions isetLayoutParams(new

GalleryLayoutParams(LayoutParamsWRAP_CONTENT LayoutParamsWRAP_CONTENT))

Add the ImageView to the layout and set the layout as the content view mLinearLayoutaddView(i)

setContentView(mLinearLayout)

In other cases you may want to handle your image resource as a Drawable object

To do so create a Drawable from the resource like so

Resources res = mContextgetResources()

Drawable myImage = resgetDrawable(Rdrawablemy_image)

Example XML

The XML snippet below shows how to add a resource Drawable to an ImageView in

the XML layout (with some red tint just for fun)

ltImageView androidlayout_width=wrap_content

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 6

androidlayout_height=wrap_content androidtint=55ff0000

androidsrc=drawablemy_imagegt

Creating from resource XML

By now you should be familiar with Androids principles of developing a User

Interface Hence you understand the power and flexibility inherent in defining

objects in XML This philosophy caries over from Views to Drawables If there is a

Drawable object that youd like to create which is not initially dependent on

variables defined by your application code or user interaction then defining the

Drawable in XML is a good option Even if you expect your Drawable to change its

properties during the users experience with your application you should consider

defining the object in XML as you can always modify properties once it is

instantiated

Once youve defined your Drawable in XML save the file in

the resdrawable directory of your project Then retrieve and instantiate the

object by calling ResourcesgetDrawable() passing it the resource ID of your XML

file (See the example below)

Any Drawable subclass that supports the inflate() method can be defined in XML

and instantiated by your application Each Drawable that supports XML inflation

utilizes specific XML attributes that help define the object properties (see the class

reference to see what these are) See the class documentation for each Drawable

subclass for information on how to define it in XML

Example

Heres some XML that defines a TransitionDrawable

lttransition xmlnsandroid=httpschemasandroidcomapkresandroidgt ltitem androiddrawable=drawableimage_expandgt ltitem androiddrawable=drawableimage_collapsegt

lttransitiongt

With this XML saved in the file resdrawableexpand_collapsexml the following

code will instantiate the TransitionDrawable and set it as the content of an

ImageView

Resources res = mContextgetResources() TransitionDrawable transition = (TransitionDrawable)

resgetDrawable(Rdrawableexpand_collapse)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 7

ImageView image = (ImageView) findViewById(Ridtoggle_image)

imagesetImageDrawable(transition)

Then this transition can be run forward (for 1 second) with

transitionstartTransition(1000)

Canvas class

The Canvas class holds the draw calls To draw something you need 4 basic

components A Bitmap to hold the pixels a Canvas to host the draw calls (writing

into the bitmap) a drawing primitive (eg Rect Path text Bitmap) and a paint (to

describe the colors and styles for the drawing)

Public Constructors

Canvas() Construct an empty raster canvas

Canvas(Bitmap bitmap) Construct a canvas with the specified bitmap to draw into

Public Methods

void drawArc(RectF oval float startAngle float sweepAngle boolean useCenter Paint paint)

Draw the specified arc which will be scaled to fit inside the specified

oval

void drawBitmap(Bitmap bitmap float left float top Paint paint) Draw the specified bitmap with its topleft corner at (xy) using the

specified paint transformed by the current matrix

void drawCircle(float cx float cy float radius Paint paint) Draw the specified circle using the specified paint

void drawColor(int color) Fill the entire canvas bitmap (restricted to the current clip) with the specified color using srcover porterduff mode

void drawLine(float startX float startY float stopX float stopY Paint paint)

Draw a line segment with the specified start and stop xy coordinates using the specified paint

void drawLines(float[] pts Paint paint)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 8

void drawLines(float[] pts int offset int count Paint paint)

Draw a series of lines

void drawOval(RectF oval Paint paint)

Draw the specified oval using the specified paint

void drawPaint(Paint paint)

Fill the entire canvas bitmap (restricted to the current clip) with the specified paint

void drawPicture(Picture picture) Save the canvas state draw the picture and restore the canvas state

void drawPicture(Picture picture Rect dst) Draw the picture stretched to fit into the dst rectangle

void drawPoint(float x float y Paint paint) Helper for drawPoints() for drawing a single point

void drawPoints(float[] pts int offset int count Paint paint) Draw a series of points

void drawPoints(float[] pts Paint paint) Helper for drawPoints() that assumes you want to draw the entire

array

void drawPosText(char[] text int index int count float[] pos Paint paint)

Draw the text in the array with each characters origin specified by the pos array

void drawPosText(String text float[] pos Paint paint) Draw the text in the array with each characters origin specified by the pos array

void drawRGB(int r int g int b) Fill the entire canvas bitmap (restricted to the current clip) with the

specified RGB color using srcover porterduff mode

void drawRect(float left float top float right float bottom Paint paint)

Draw the specified Rect using the specified paint

void drawRect(RectF rect Paint paint)

Draw the specified Rect using the specified paint

void drawRect(Rect r Paint paint)

Draw the specified Rect using the specified Paint

void drawRoundRect(RectF rect float rx float ry Paint paint)

Draw the specified round-rect using the specified paint

void drawText(String text float x float y Paint paint)

Draw the text with origin at (xy) using the specified paint

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 9

void drawText(CharSequence text int start int end float x float

y Paint paint) Draw the specified range of text specified by startend with its origin at (xy) in the specified Paint

void drawText(char[] text int index int count float x float y Paint paint) Draw the text with origin at (xy) using the specified paint

void drawText(String text int start int end float x float y Paint paint) Draw the text with origin at (xy) using the specified paint

void drawTextOnPath(String text Path path float hOffset float vOffset Paint paint)

Draw the text with origin at (xy) using the specified paint along the specified path

void drawTextOnPath(char[] text int index int count Path path float hOffset float vOffset Paint paint)

Draw the text with origin at (xy) using the specified paint along the specified path

int getHeight() Returns the height of the current drawing layer

void getMatrix(Matrix ctm) Return in ctm the current transformation matrix

final Matrix

getMatrix() Return a new matrix with a copy of the canvas current transformation matrix

int getWidth() Returns the width of the current drawing layer

void rotate(float degrees) Preconcat the current matrix with the specified rotation

final void

rotate(float degrees float px float py) Preconcat the current matrix with the specified rotation

void scale(float sx float sy) Preconcat the current matrix with the specified scale

final

void scale(float sx float sy float px float py)

Preconcat the current matrix with the specified scale

void setBitmap(Bitmap bitmap)

Specify a bitmap for the canvas to draw into

void translate(float dx float dy)

Preconcat the current matrix with the specified translation

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 10

Paint class

The Paint class holds the style and color information about how to draw

geometries text and bitmaps

Paint Styles

public static final PaintStyle FILL

Geometry and text drawn with this style will be filled ignoring all stroke-related

settings in the paint

public static final PaintStyle FILL_AND_STROKE

Geometry and text drawn with this style will be both filled and stroked at the same time respecting the stroke-related fields on the paint This mode can give unexpected results if the geometry is oriented counter-clockwise This restriction

does not apply to either FILL or STROKE

public static final PaintStyle STROKE

Geometry and text drawn with this style will be stroked respecting the stroke-related fields on the paint

Public Constructors

Paint()

Create a new paint with default settings

Paint(int flags)

Create a new paint with the specified flags

Paint(Paint paint)

Create a new paint initialized with the attributes in the specified paint parameter

Public Methods

int getAlpha()

Helper to getColor() that just returns the colors alpha value

int getColor()

Return the paints color

ColorFilter getColorFilter()

Get the paints colorfilter (maybe be null)

boolean

getFillPath(Path src Path dst)

Applies anyall effects (patheffect stroking) to src returning

the result in dst

int getFlags()

Return the paints flags

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 11

PaintFontMetrics

getFontMetrics()

Allocates a new FontMetrics object and then calls

getFontMetrics(fm) with it returning the object

int

getFontMetricsInt(PaintFontMetricsInt fmi)

Return the fonts interline spacing given the Paints settings

for typeface textSize etc

float

getFontSpacing()

Return the recommend line spacing based on the current

typeface and text size

MaskFilter getMaskFilter()

Get the paints maskfilter object

Shader getShader()

Get the paints shader object

PaintStyle

getStyle()

Return the paints style used for controlling how primitives

geometries are interpreted (except for drawBitmap which

always assumes FILL_STYLE)

PaintAlign getTextAlign()

Return the paints Align value for drawing text

void

getTextBounds(char[] text int index int count Rect bounds)

Return in bounds (allocated by the caller) the smallest

rectangle that encloses all of the characters with an implied

origin at (00)

void

getTextBounds(String text int start int end Rect bounds)

Return in bounds (allocated by the caller) the smallest

rectangle that encloses all of the characters with an implied

origin at (00)

void

getTextPath(String text int start int end float x float y Path

path)

Return the path (outline) for the specified text

void

getTextPath(char[] text int index int count float x float y

Path path)

Return the path (outline) for the specified text

float getTextScaleX()

Return the paints horizontal scale factor for text

float getTextSize()

Return the paints text size

int getTextWidths(String text float[] widths)

Return the advance widths for the characters in the string

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 12

int

getTextWidths(CharSequence text int start int end float[]

widths)

Return the advance widths for the characters in the string

int getTextWidths(String text int start int end float[] widths)

Return the advance widths for the characters in the string

int getTextWidths(char[] text int index int count float[] widths)

Return the advance widths for the characters in the string

Typeface getTypeface()

Get the paints typeface object

final boolean

isAntiAlias()

Helper for getFlags() returning true if ANTI_ALIAS_FLAG bit is

set AntiAliasing smooths out the edges of what is being

drawn but is has no impact on the interior of the shape

final boolean

isStrikeThruText()

Helper for getFlags() returning true if

STRIKE_THRU_TEXT_FLAG bit is set

final boolean

isSubpixelText()

Helper for getFlags() returning true if SUBPIXEL_TEXT_FLAG

bit is set

final boolean

isUnderlineText()

Helper for getFlags() returning true if

UNDERLINE_TEXT_FLAG bit is set

float measureText(String text)

Return the width of the text

float measureText(CharSequence text int start int end)

Return the width of the text

float measureText(String text int start int end)

Return the width of the text

float measureText(char[] text int index int count)

Return the width of the text

void reset()

Restores the paint to its default settings

void set(Paint src)

Copy the fields from src into this paint

void

setARGB(int a int r int g int b)

Helper to setColor() that takes argb and constructs the

color int

void setAlpha(int a)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 13

Helper to setColor() that only assigns the colors alpha value

leaving its rgb values unchanged

void

setAntiAlias(boolean aa)

Helper for setFlags() setting or clearing the ANTI_ALIAS_FLAG

bit AntiAliasing smooths out the edges of what is being drawn

but is has no impact on the interior of the shape

void setColor(int color)

Set the paints color

ColorFilter setColorFilter(ColorFilter filter)

Set or clear the paints colorfilter returning the parameter

void

setFakeBoldText(boolean fakeBoldText)

Helper for setFlags() setting or clearing the

FAKE_BOLD_TEXT_FLAG bit

void setFlags(int flags)

Set the paints flags

PathEffect setPathEffect(PathEffect effect)

Set or clear the patheffect object

Shader setShader(Shader shader)

Set or clear the shader object

void

setShadowLayer(float radius float dx float dy int color)

This draws a shadow layer below the main layer with the

specified offset and color and blur radius

void

setStrikeThruText(boolean strikeThruText)

Helper for setFlags() setting or clearing the

STRIKE_THRU_TEXT_FLAG bit

void

setStyle(PaintStyle style)

Set the paints style used for controlling how primitives

geometries are interpreted (except for drawBitmap which

always assumes Fill)

void

setSubpixelText(boolean subpixelText)

Helper for setFlags() setting or clearing the

SUBPIXEL_TEXT_FLAG bit

void setTextAlign(PaintAlign align)

Set the paints text alignment

void setTextSize(float textSize)

Set the paints text size

void setTextSkewX(float skewX)

Set the paints horizontal skew factor for text

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 14

Typeface setTypeface(Typeface typeface)

Set or clear the typeface object

void

setUnderlineText(boolean underlineText)

Helper for setFlags() setting or clearing the

UNDERLINE_TEXT_FLAG bit

Types of Gradient

1 Linear Gradient

public LinearGradient (float x0 float y0 float x1 float y1 int[] colors float[]

positions ShaderTileMode tile)

Create a shader that draws a linear gradient along a line

Parameters

x0 The x-coordinate for the start of the gradient line

y0 The y-coordinate for the start of the gradient line

x1 The x-coordinate for the end of the gradient line

y1 The y-coordinate for the end of the gradient line

colors The colors to be distributed along the gradient line

positions

May be null The relative positions [01] of each corresponding color in

the colors array If this is null the the colors are distributed evenly

along the gradient line

tile The Shader tiling mode

2 Sweep Gradient

public SweepGradient (float cx float cy int[] colors float[] positions)

A subclass of Shader that draws a sweep gradient around a center point

Parameters

cx The x-coordinate of the center

cy The y-coordinate of the center

colors The colors to be distributed between around the center There must be

at least 2 colors in the array

positions

May be NULL The relative position of each corresponding color in the

colors array beginning with 0 and ending with 10 If the values are not

monotonic the drawing may produce unexpected results If positions is

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 15

NULL then the colors are automatically spaced evenly

3 Radial Gradient

public RadialGradient (float x float y float radius int[] colors float[] positions

ShaderTileMode tile)

Create a shader that draws a radial gradient given the center and radius

Parameters

x The x-coordinate of the center of the radius

y The y-coordinate of the center of the radius

radius Must be positive The radius of the circle for this gradient

colors The colors to be distributed between the center and edge of the circle

positions

May be NULL The relative position of each corresponding color in the

colors array If this is NULL the the colors are distributed evenly

between the center and edge of the circle

tile The Shader tiling mode

Shader Class

Shader is the based class for objects that return horizontal spans of colors during

drawing A subclass of Shader is installed in a Paint calling

paintsetShader(shader) After that any object (other than a bitmap) that is drawn

with that paint will get its color(s) from the shader

ShaderTileMode CLAMP replicate the edge color if the shader draws

outside of its original bounds

ShaderTileMode MIRROR repeat the shaders image horizontally and

vertically alternating mirror images so that adjacent images always seam

ShaderTileMode REPEAT repeat the shaders image horizontally and

vertically

Color

The Color class defines methods for creating and converting color ints Colors are

represented as packed ints made up of 4 bytes alpha red green blue The

values are unpremultiplied meaning any transparency is stored solely in the

alpha component and not in the color components The components are stored as

follows (alpha ltlt 24) | (red ltlt 16) | (green ltlt 8) | blue Each component ranges

between 0255 with 0 meaning no contribution for that component and 255

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 16

meaning 100 contribution Thus opaque-black would be 0xFF000000 (100

opaque but no contributions from red green or blue) and opaque-white would be

0xFFFFFFFF

Constant

int BLACK int LTGRAY

int BLUE int MAGENTA

int CYAN int RED

int DKGRAY int TRANSPARENT

int GRAY int WHITE

int GREEN int YELLOW

Public Constructors

Color()

Public Methods

static int HSVToColor(float[] hsv)

Convert HSV components to an ARGB color

static int HSVToColor(int alpha float[] hsv)

Convert HSV components to an ARGB color

static void RGBToHSV(int red int green int blue float[] hsv)

Convert RGB components to HSV

static int alpha(int color)

Return the alpha component of a color int

static int argb(int alpha int red int green int blue)

Return a color-int from alpha red green blue components

static int blue(int color)

Return the blue component of a color int

static void colorToHSV(int color float[] hsv)

Convert the argb color to its HSV components

static int green(int color)

Return the green component of a color int

static int parseColor(String colorString)

Parse the color string and return the corresponding color-int

static int red(int color)

Return the red component of a color int

static int rgb(int red int green int blue)

Return a color-int from red green blue components

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 17

Working with Text

Android provide several default fonts typeface and styles Application can also use

custom fonts by including font files as application assets and loading them using

the AssetManger same as recourses

Typeface class

The Typeface class specifies the typeface and intrinsic style of a font This is used

in the paint along with optionally Paint settings like textSize textSkewX

textScaleX to specify how text appears when drawn (and measured)

Constant

int BOLD

int BOLD_ITALIC

int ITALIC

int NORMAL

Fields

public static

final Typeface DEFAULT The default NORMAL typeface object

public static

final Typeface DEFAULT_BOLD The default BOLD typeface object

public static

final Typeface MONOSPACE The NORMAL style of the default monospace typeface

public static

final Typeface SANS_SERIF The NORMAL style of the default sans serif typeface

public static

final Typeface SERIF The NORMAL style of the default serif typeface

Public Methods

static

Typeface

create(String familyName int style)

Create a typeface object given a family name and option style

information

static

Typeface

create(Typeface family int style)

Create a typeface object that best matches the specified existing typeface

and the specified Style

static

Typeface

createFromAsset(AssetManager mgr String path)

Create a new typeface from the specified font data

static

Typeface

createFromFile(String path)

Create a new typeface from the specified font file

static createFromFile(File path)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 18

Typeface Create a new typeface from the specified font file

static

Typeface

defaultFromStyle(int style)

Returns one of the default typeface objects based on the specified style

int getStyle()

Returns the typefaces intrinsic style attributes

final

boolean

isBold()

Returns true if getStyle() has the BOLD bit set

final

boolean

isItalic()

Returns true if getStyle() has the ITALIC bit set

Using Default Fonts and Typefaces

By default Android uses the Sans Serif typeface but Monospace and Serif

typefaces are also available The following code excerpt draws some antialiased text in the default typeface (Sans Serif) to a Canvas

import androidgraphicsCanvas import androidgraphicsColor import androidgraphicsPaint import androidgraphicsTypeface Paint mPaint = new Paint(PaintANTI_ALIAS_FLAG) Typeface mType mPaintsetTextSize(16) mPaintsetTypeface(null) canvasdrawText(ldquoDefault Typefacerdquo 20 20 mPaint) You can instead load a different typeface such as Monotype

Typeface mType = Typefacecreate(TypefaceMONOSPACE TypefaceNORMAL) Perhaps you would prefer italic text in which case you can simply set the style of the typeface and the font family

Typeface mType = Typefacecreate(TypefaceSERIF TypefaceITALIC)

You can set certain properties of a typeface such as antialiasing underlining and strikethrough using the setFlags() method of the Paint object

mPaintsetFlags(PaintUNDERLINE_TEXT_FLAG)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 19

Loading Custom typeface from asset

Typeface mType = TypefacecreateFromAsset(getContext()getAssets()ldquofontschess1ttfrdquo) Example ViewFontjava

package compritesh

import androidcontentContext import androidgraphicsCanvas import androidgraphicsColor import androidgraphicsPaint import androidgraphicsTypeface import androidviewView public class ViewFont extends View Context c public ViewFont(Context context) super(context) c=context protected void onDraw(Canvas canvas) Typeface mType = TypefacecreateFromAsset( cgetAssets() fontsBaroqueScriptttf) Paint p =new Paint(PaintANTI_ALIAS_FLAG) psetTypeface(mType) psetTextSize(20) canvasdrawColor(ColorBLUE) canvasdrawText(Welcome to Android canvasgetWidth()4 canvasgetHeight()3 p)

SampleCustomFontjava package compritesh import androidappActivity import androidgraphicsTypeface import androidosBundle public class SampleCustomFont extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain) setContentView(new ViewFont(this))

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 20

Working with Bitmap and Matrix Bitmap

In computer graphics a bitmap or pixmap is a type of memory organization

or image file format used to store digital images The term bitmap comes from the

computer programming terminology meaning just a map of bits a spatially mapped array of bits Now along with pixmap it commonly refers to the similar

concept of a spatially mapped array of pixels Raster images in general may be referred to as bitmaps or pixmaps whether synthetic or photographic in files or

memory In certain contexts the term bitmap implies one bit per pixel while pixmap

is used for images with multiple bits per pixel

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 21

Shape Drawable in XML

This is a generic shape defined in XML

File location

resdrawablefilenamexml

The filename is used as the resource ID

Compiled resource datatype

Resource pointer to a GradientDrawable

Resource reference

In Java Rdrawablefilename

In XML [package]drawablefilename

Syntax

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=[rectangle | oval | line | ring] gt ltcorners androidradius=integer androidtopLeftRadius=integer androidtopRightRadius=integer androidbottomLeftRadius=integer androidbottomRightRadius=integer gt ltgradient androidangle=integer androidcenterX=integer androidcenterY=integer androidcenterColor=integer androidendColor=color androidgradientRadius=integer androidstartColor=color androidtype=[linear | radial | sweep] androidusesLevel=[true | false] gt ltpadding androidleft=integer androidtop=integer androidright=integer androidbottom=integer gt ltsize androidwidth=integer androidheight=integer gt ltsolid

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 22

androidcolor=color gt ltstroke androidwidth=integer androidcolor=color androiddashWidth=integer androiddashGap=integer gt ltshapegt

Elements

ltshapegt

The shape drawable This must be the root element

Attributes

xmlnsandroid

String Required Defines the XML namespace which must be

httpschemasandroidcomapkresandroid

androidshape

Keyword Defines the type of shape Valid values are

Value Desciption

rectangle A rectangle that fills the containing View This is the default shape

oval An oval shape that fits the dimensions of the containing View

line A horizontal line that spans the width of the containing View This

shape requires the ltstrokegt element to define the width of the line

ring A ring shape

The following attributes are used only when androidshape=ring

androidinnerRadius

Dimension The radius for the inner part of the ring (the hole in the middle)

as a dimension value or dimension resource

androidinnerRadiusRatio

Float The radius for the inner part of the ring expressed as a ratio of the

rings width For instance if androidinnerRadiusRatio=5 then the inner

radius equals the rings width divided by 5 This value is overridden by

androidinnerRadius Default value is 9

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 23

androidthickness

Dimension The thickness of the ring as a dimension value or dimension

resource

androidthicknessRatio

Float The thickness of the ring expressed as a ratio of the rings width For

instance if androidthicknessRatio=2 then the thickness equals the rings

width divided by 2 This value is overridden by androidinnerRadius Default

value is 3

androiduseLevel

Boolean true if this is used as a LevelListDrawable This should normally

be false or your shape may not appear

ltcornersgt

Creates rounded corners for the shape Applies only when the shape is a

rectangle

Attributes

androidradius

Dimension The radius for all corners as a dimension value or dimension

resource This is overridden for each corner by the following attributes

androidtopLeftRadius

Dimension The radius for the top-left corner as a dimension value or

dimension resource

androidtopRightRadius

Dimension The radius for the top-right corner as a dimension value or

dimension resource

androidbottomLeftRadius

Dimension The radius for the bottom-left corner as a dimension value or

dimension resource

androidbottomRightRadius

Dimension The radius for the bottom-right corner as a dimension value or

dimension resource

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 24

Note Every corner must (initially) be provided a corner radius greater than

1 or else no corners are rounded If you want specific corners to not be rounded a work-around is to use androidradius to set a default corner

radius greater than 1 but then override each and every corner with the values you really want providing zero (0dp) where you dont want rounded

corners

ltgradientgt

Specifies a gradient color for the shape

Attributes

androidangle

Integer The angle for the gradient in degrees 0 is left to right 90 is bottom

to top It must be a multiple of 45 Default is 0

androidcenterX

Float The relative X-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterY

Float The relative Y-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterColor

Color Optional color that comes between the start and end colors as a

hexadecimal value or color resource

androidendColor

Color The ending color as a hexadecimal value or color resource

androidgradientRadius

Float The radius for the gradient Only applied when androidtype=radial

androidstartColor

Color The starting color as a hexadecimal value or color resource

androidtype

Keyword The type of gradient pattern to apply Valid values are

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 25

Value Description

linear A linear gradient This is the default

radial A radial gradient The start color is the center color

sweep A sweeping line gradient

androiduseLevel

Boolean true if this is used as a LevelListDrawable

ltpaddinggt

Padding to apply to the containing View element (this pads the position of

the View content not the shape)

Attributes

androidleft

Dimension Left padding as a dimension value or dimension resource

androidtop

Dimension Top padding as a dimension value or dimension resource

androidright

Dimension Right padding as a dimension value or dimension resource

androidbottom

Dimension Bottom padding as a dimension value or dimension resource

ltsizegt

The size of the shape

Attributes

androidheight

Dimension The height of the shape as a dimension value or dimension

resource

androidwidth

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 26

Dimension The width of the shape as a dimension value or dimension

resource

Note The shape scales to the size of the container View proportionate to the

dimensions defined here by default When you use the shape in an ImageView you can restrict scaling by setting the androidscaleType to center

ltsolidgt

A solid color to fill the shape

Attributes

androidcolor

Color The color to apply to the shape as a hexadecimal value or color

resource

ltstrokegt

A stroke line for the shape

Attributes

androidwidth

Dimension The thickness of the line as a dimension value or dimension

resource

androidcolor

Color The color of the line as a hexadecimal value or color resource

androiddashGap

Dimension The distance between line dashes as a dimension value or

dimension resource Only valid if androiddashWidth is set

androiddashWidth

Dimension The size of each dash line as a dimension value or dimension

resource Only valid if androiddashGap is set

Example

XML file saved at resdrawablegradient_boxxml

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 27

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=rectanglegt ltgradient androidstartColor=FFFF0000 androidendColor=80FF00FF androidangle=45gt ltpadding androidleft=7dp androidtop=7dp androidright=7dp androidbottom=7dp gt ltcorners androidradius=8dp gt ltshapegt

This layout XML applies the shape drawable to a View

ltTextView androidbackground=drawablegradient_box androidlayout_height=wrap_content androidlayout_width=wrap_content gt

This application code gets the shape drawable and applies it to a View

Resources res = getResources() Drawable shape = res getDrawable(Rdrawablegradient_box)

TextView tv = (TextView)findViewByID(Ridtextview) tvsetBackground(shape)

Page 6: Android graphics mca 5th

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 6

androidlayout_height=wrap_content androidtint=55ff0000

androidsrc=drawablemy_imagegt

Creating from resource XML

By now you should be familiar with Androids principles of developing a User

Interface Hence you understand the power and flexibility inherent in defining

objects in XML This philosophy caries over from Views to Drawables If there is a

Drawable object that youd like to create which is not initially dependent on

variables defined by your application code or user interaction then defining the

Drawable in XML is a good option Even if you expect your Drawable to change its

properties during the users experience with your application you should consider

defining the object in XML as you can always modify properties once it is

instantiated

Once youve defined your Drawable in XML save the file in

the resdrawable directory of your project Then retrieve and instantiate the

object by calling ResourcesgetDrawable() passing it the resource ID of your XML

file (See the example below)

Any Drawable subclass that supports the inflate() method can be defined in XML

and instantiated by your application Each Drawable that supports XML inflation

utilizes specific XML attributes that help define the object properties (see the class

reference to see what these are) See the class documentation for each Drawable

subclass for information on how to define it in XML

Example

Heres some XML that defines a TransitionDrawable

lttransition xmlnsandroid=httpschemasandroidcomapkresandroidgt ltitem androiddrawable=drawableimage_expandgt ltitem androiddrawable=drawableimage_collapsegt

lttransitiongt

With this XML saved in the file resdrawableexpand_collapsexml the following

code will instantiate the TransitionDrawable and set it as the content of an

ImageView

Resources res = mContextgetResources() TransitionDrawable transition = (TransitionDrawable)

resgetDrawable(Rdrawableexpand_collapse)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 7

ImageView image = (ImageView) findViewById(Ridtoggle_image)

imagesetImageDrawable(transition)

Then this transition can be run forward (for 1 second) with

transitionstartTransition(1000)

Canvas class

The Canvas class holds the draw calls To draw something you need 4 basic

components A Bitmap to hold the pixels a Canvas to host the draw calls (writing

into the bitmap) a drawing primitive (eg Rect Path text Bitmap) and a paint (to

describe the colors and styles for the drawing)

Public Constructors

Canvas() Construct an empty raster canvas

Canvas(Bitmap bitmap) Construct a canvas with the specified bitmap to draw into

Public Methods

void drawArc(RectF oval float startAngle float sweepAngle boolean useCenter Paint paint)

Draw the specified arc which will be scaled to fit inside the specified

oval

void drawBitmap(Bitmap bitmap float left float top Paint paint) Draw the specified bitmap with its topleft corner at (xy) using the

specified paint transformed by the current matrix

void drawCircle(float cx float cy float radius Paint paint) Draw the specified circle using the specified paint

void drawColor(int color) Fill the entire canvas bitmap (restricted to the current clip) with the specified color using srcover porterduff mode

void drawLine(float startX float startY float stopX float stopY Paint paint)

Draw a line segment with the specified start and stop xy coordinates using the specified paint

void drawLines(float[] pts Paint paint)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 8

void drawLines(float[] pts int offset int count Paint paint)

Draw a series of lines

void drawOval(RectF oval Paint paint)

Draw the specified oval using the specified paint

void drawPaint(Paint paint)

Fill the entire canvas bitmap (restricted to the current clip) with the specified paint

void drawPicture(Picture picture) Save the canvas state draw the picture and restore the canvas state

void drawPicture(Picture picture Rect dst) Draw the picture stretched to fit into the dst rectangle

void drawPoint(float x float y Paint paint) Helper for drawPoints() for drawing a single point

void drawPoints(float[] pts int offset int count Paint paint) Draw a series of points

void drawPoints(float[] pts Paint paint) Helper for drawPoints() that assumes you want to draw the entire

array

void drawPosText(char[] text int index int count float[] pos Paint paint)

Draw the text in the array with each characters origin specified by the pos array

void drawPosText(String text float[] pos Paint paint) Draw the text in the array with each characters origin specified by the pos array

void drawRGB(int r int g int b) Fill the entire canvas bitmap (restricted to the current clip) with the

specified RGB color using srcover porterduff mode

void drawRect(float left float top float right float bottom Paint paint)

Draw the specified Rect using the specified paint

void drawRect(RectF rect Paint paint)

Draw the specified Rect using the specified paint

void drawRect(Rect r Paint paint)

Draw the specified Rect using the specified Paint

void drawRoundRect(RectF rect float rx float ry Paint paint)

Draw the specified round-rect using the specified paint

void drawText(String text float x float y Paint paint)

Draw the text with origin at (xy) using the specified paint

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 9

void drawText(CharSequence text int start int end float x float

y Paint paint) Draw the specified range of text specified by startend with its origin at (xy) in the specified Paint

void drawText(char[] text int index int count float x float y Paint paint) Draw the text with origin at (xy) using the specified paint

void drawText(String text int start int end float x float y Paint paint) Draw the text with origin at (xy) using the specified paint

void drawTextOnPath(String text Path path float hOffset float vOffset Paint paint)

Draw the text with origin at (xy) using the specified paint along the specified path

void drawTextOnPath(char[] text int index int count Path path float hOffset float vOffset Paint paint)

Draw the text with origin at (xy) using the specified paint along the specified path

int getHeight() Returns the height of the current drawing layer

void getMatrix(Matrix ctm) Return in ctm the current transformation matrix

final Matrix

getMatrix() Return a new matrix with a copy of the canvas current transformation matrix

int getWidth() Returns the width of the current drawing layer

void rotate(float degrees) Preconcat the current matrix with the specified rotation

final void

rotate(float degrees float px float py) Preconcat the current matrix with the specified rotation

void scale(float sx float sy) Preconcat the current matrix with the specified scale

final

void scale(float sx float sy float px float py)

Preconcat the current matrix with the specified scale

void setBitmap(Bitmap bitmap)

Specify a bitmap for the canvas to draw into

void translate(float dx float dy)

Preconcat the current matrix with the specified translation

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 10

Paint class

The Paint class holds the style and color information about how to draw

geometries text and bitmaps

Paint Styles

public static final PaintStyle FILL

Geometry and text drawn with this style will be filled ignoring all stroke-related

settings in the paint

public static final PaintStyle FILL_AND_STROKE

Geometry and text drawn with this style will be both filled and stroked at the same time respecting the stroke-related fields on the paint This mode can give unexpected results if the geometry is oriented counter-clockwise This restriction

does not apply to either FILL or STROKE

public static final PaintStyle STROKE

Geometry and text drawn with this style will be stroked respecting the stroke-related fields on the paint

Public Constructors

Paint()

Create a new paint with default settings

Paint(int flags)

Create a new paint with the specified flags

Paint(Paint paint)

Create a new paint initialized with the attributes in the specified paint parameter

Public Methods

int getAlpha()

Helper to getColor() that just returns the colors alpha value

int getColor()

Return the paints color

ColorFilter getColorFilter()

Get the paints colorfilter (maybe be null)

boolean

getFillPath(Path src Path dst)

Applies anyall effects (patheffect stroking) to src returning

the result in dst

int getFlags()

Return the paints flags

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 11

PaintFontMetrics

getFontMetrics()

Allocates a new FontMetrics object and then calls

getFontMetrics(fm) with it returning the object

int

getFontMetricsInt(PaintFontMetricsInt fmi)

Return the fonts interline spacing given the Paints settings

for typeface textSize etc

float

getFontSpacing()

Return the recommend line spacing based on the current

typeface and text size

MaskFilter getMaskFilter()

Get the paints maskfilter object

Shader getShader()

Get the paints shader object

PaintStyle

getStyle()

Return the paints style used for controlling how primitives

geometries are interpreted (except for drawBitmap which

always assumes FILL_STYLE)

PaintAlign getTextAlign()

Return the paints Align value for drawing text

void

getTextBounds(char[] text int index int count Rect bounds)

Return in bounds (allocated by the caller) the smallest

rectangle that encloses all of the characters with an implied

origin at (00)

void

getTextBounds(String text int start int end Rect bounds)

Return in bounds (allocated by the caller) the smallest

rectangle that encloses all of the characters with an implied

origin at (00)

void

getTextPath(String text int start int end float x float y Path

path)

Return the path (outline) for the specified text

void

getTextPath(char[] text int index int count float x float y

Path path)

Return the path (outline) for the specified text

float getTextScaleX()

Return the paints horizontal scale factor for text

float getTextSize()

Return the paints text size

int getTextWidths(String text float[] widths)

Return the advance widths for the characters in the string

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 12

int

getTextWidths(CharSequence text int start int end float[]

widths)

Return the advance widths for the characters in the string

int getTextWidths(String text int start int end float[] widths)

Return the advance widths for the characters in the string

int getTextWidths(char[] text int index int count float[] widths)

Return the advance widths for the characters in the string

Typeface getTypeface()

Get the paints typeface object

final boolean

isAntiAlias()

Helper for getFlags() returning true if ANTI_ALIAS_FLAG bit is

set AntiAliasing smooths out the edges of what is being

drawn but is has no impact on the interior of the shape

final boolean

isStrikeThruText()

Helper for getFlags() returning true if

STRIKE_THRU_TEXT_FLAG bit is set

final boolean

isSubpixelText()

Helper for getFlags() returning true if SUBPIXEL_TEXT_FLAG

bit is set

final boolean

isUnderlineText()

Helper for getFlags() returning true if

UNDERLINE_TEXT_FLAG bit is set

float measureText(String text)

Return the width of the text

float measureText(CharSequence text int start int end)

Return the width of the text

float measureText(String text int start int end)

Return the width of the text

float measureText(char[] text int index int count)

Return the width of the text

void reset()

Restores the paint to its default settings

void set(Paint src)

Copy the fields from src into this paint

void

setARGB(int a int r int g int b)

Helper to setColor() that takes argb and constructs the

color int

void setAlpha(int a)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 13

Helper to setColor() that only assigns the colors alpha value

leaving its rgb values unchanged

void

setAntiAlias(boolean aa)

Helper for setFlags() setting or clearing the ANTI_ALIAS_FLAG

bit AntiAliasing smooths out the edges of what is being drawn

but is has no impact on the interior of the shape

void setColor(int color)

Set the paints color

ColorFilter setColorFilter(ColorFilter filter)

Set or clear the paints colorfilter returning the parameter

void

setFakeBoldText(boolean fakeBoldText)

Helper for setFlags() setting or clearing the

FAKE_BOLD_TEXT_FLAG bit

void setFlags(int flags)

Set the paints flags

PathEffect setPathEffect(PathEffect effect)

Set or clear the patheffect object

Shader setShader(Shader shader)

Set or clear the shader object

void

setShadowLayer(float radius float dx float dy int color)

This draws a shadow layer below the main layer with the

specified offset and color and blur radius

void

setStrikeThruText(boolean strikeThruText)

Helper for setFlags() setting or clearing the

STRIKE_THRU_TEXT_FLAG bit

void

setStyle(PaintStyle style)

Set the paints style used for controlling how primitives

geometries are interpreted (except for drawBitmap which

always assumes Fill)

void

setSubpixelText(boolean subpixelText)

Helper for setFlags() setting or clearing the

SUBPIXEL_TEXT_FLAG bit

void setTextAlign(PaintAlign align)

Set the paints text alignment

void setTextSize(float textSize)

Set the paints text size

void setTextSkewX(float skewX)

Set the paints horizontal skew factor for text

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 14

Typeface setTypeface(Typeface typeface)

Set or clear the typeface object

void

setUnderlineText(boolean underlineText)

Helper for setFlags() setting or clearing the

UNDERLINE_TEXT_FLAG bit

Types of Gradient

1 Linear Gradient

public LinearGradient (float x0 float y0 float x1 float y1 int[] colors float[]

positions ShaderTileMode tile)

Create a shader that draws a linear gradient along a line

Parameters

x0 The x-coordinate for the start of the gradient line

y0 The y-coordinate for the start of the gradient line

x1 The x-coordinate for the end of the gradient line

y1 The y-coordinate for the end of the gradient line

colors The colors to be distributed along the gradient line

positions

May be null The relative positions [01] of each corresponding color in

the colors array If this is null the the colors are distributed evenly

along the gradient line

tile The Shader tiling mode

2 Sweep Gradient

public SweepGradient (float cx float cy int[] colors float[] positions)

A subclass of Shader that draws a sweep gradient around a center point

Parameters

cx The x-coordinate of the center

cy The y-coordinate of the center

colors The colors to be distributed between around the center There must be

at least 2 colors in the array

positions

May be NULL The relative position of each corresponding color in the

colors array beginning with 0 and ending with 10 If the values are not

monotonic the drawing may produce unexpected results If positions is

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 15

NULL then the colors are automatically spaced evenly

3 Radial Gradient

public RadialGradient (float x float y float radius int[] colors float[] positions

ShaderTileMode tile)

Create a shader that draws a radial gradient given the center and radius

Parameters

x The x-coordinate of the center of the radius

y The y-coordinate of the center of the radius

radius Must be positive The radius of the circle for this gradient

colors The colors to be distributed between the center and edge of the circle

positions

May be NULL The relative position of each corresponding color in the

colors array If this is NULL the the colors are distributed evenly

between the center and edge of the circle

tile The Shader tiling mode

Shader Class

Shader is the based class for objects that return horizontal spans of colors during

drawing A subclass of Shader is installed in a Paint calling

paintsetShader(shader) After that any object (other than a bitmap) that is drawn

with that paint will get its color(s) from the shader

ShaderTileMode CLAMP replicate the edge color if the shader draws

outside of its original bounds

ShaderTileMode MIRROR repeat the shaders image horizontally and

vertically alternating mirror images so that adjacent images always seam

ShaderTileMode REPEAT repeat the shaders image horizontally and

vertically

Color

The Color class defines methods for creating and converting color ints Colors are

represented as packed ints made up of 4 bytes alpha red green blue The

values are unpremultiplied meaning any transparency is stored solely in the

alpha component and not in the color components The components are stored as

follows (alpha ltlt 24) | (red ltlt 16) | (green ltlt 8) | blue Each component ranges

between 0255 with 0 meaning no contribution for that component and 255

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 16

meaning 100 contribution Thus opaque-black would be 0xFF000000 (100

opaque but no contributions from red green or blue) and opaque-white would be

0xFFFFFFFF

Constant

int BLACK int LTGRAY

int BLUE int MAGENTA

int CYAN int RED

int DKGRAY int TRANSPARENT

int GRAY int WHITE

int GREEN int YELLOW

Public Constructors

Color()

Public Methods

static int HSVToColor(float[] hsv)

Convert HSV components to an ARGB color

static int HSVToColor(int alpha float[] hsv)

Convert HSV components to an ARGB color

static void RGBToHSV(int red int green int blue float[] hsv)

Convert RGB components to HSV

static int alpha(int color)

Return the alpha component of a color int

static int argb(int alpha int red int green int blue)

Return a color-int from alpha red green blue components

static int blue(int color)

Return the blue component of a color int

static void colorToHSV(int color float[] hsv)

Convert the argb color to its HSV components

static int green(int color)

Return the green component of a color int

static int parseColor(String colorString)

Parse the color string and return the corresponding color-int

static int red(int color)

Return the red component of a color int

static int rgb(int red int green int blue)

Return a color-int from red green blue components

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 17

Working with Text

Android provide several default fonts typeface and styles Application can also use

custom fonts by including font files as application assets and loading them using

the AssetManger same as recourses

Typeface class

The Typeface class specifies the typeface and intrinsic style of a font This is used

in the paint along with optionally Paint settings like textSize textSkewX

textScaleX to specify how text appears when drawn (and measured)

Constant

int BOLD

int BOLD_ITALIC

int ITALIC

int NORMAL

Fields

public static

final Typeface DEFAULT The default NORMAL typeface object

public static

final Typeface DEFAULT_BOLD The default BOLD typeface object

public static

final Typeface MONOSPACE The NORMAL style of the default monospace typeface

public static

final Typeface SANS_SERIF The NORMAL style of the default sans serif typeface

public static

final Typeface SERIF The NORMAL style of the default serif typeface

Public Methods

static

Typeface

create(String familyName int style)

Create a typeface object given a family name and option style

information

static

Typeface

create(Typeface family int style)

Create a typeface object that best matches the specified existing typeface

and the specified Style

static

Typeface

createFromAsset(AssetManager mgr String path)

Create a new typeface from the specified font data

static

Typeface

createFromFile(String path)

Create a new typeface from the specified font file

static createFromFile(File path)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 18

Typeface Create a new typeface from the specified font file

static

Typeface

defaultFromStyle(int style)

Returns one of the default typeface objects based on the specified style

int getStyle()

Returns the typefaces intrinsic style attributes

final

boolean

isBold()

Returns true if getStyle() has the BOLD bit set

final

boolean

isItalic()

Returns true if getStyle() has the ITALIC bit set

Using Default Fonts and Typefaces

By default Android uses the Sans Serif typeface but Monospace and Serif

typefaces are also available The following code excerpt draws some antialiased text in the default typeface (Sans Serif) to a Canvas

import androidgraphicsCanvas import androidgraphicsColor import androidgraphicsPaint import androidgraphicsTypeface Paint mPaint = new Paint(PaintANTI_ALIAS_FLAG) Typeface mType mPaintsetTextSize(16) mPaintsetTypeface(null) canvasdrawText(ldquoDefault Typefacerdquo 20 20 mPaint) You can instead load a different typeface such as Monotype

Typeface mType = Typefacecreate(TypefaceMONOSPACE TypefaceNORMAL) Perhaps you would prefer italic text in which case you can simply set the style of the typeface and the font family

Typeface mType = Typefacecreate(TypefaceSERIF TypefaceITALIC)

You can set certain properties of a typeface such as antialiasing underlining and strikethrough using the setFlags() method of the Paint object

mPaintsetFlags(PaintUNDERLINE_TEXT_FLAG)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 19

Loading Custom typeface from asset

Typeface mType = TypefacecreateFromAsset(getContext()getAssets()ldquofontschess1ttfrdquo) Example ViewFontjava

package compritesh

import androidcontentContext import androidgraphicsCanvas import androidgraphicsColor import androidgraphicsPaint import androidgraphicsTypeface import androidviewView public class ViewFont extends View Context c public ViewFont(Context context) super(context) c=context protected void onDraw(Canvas canvas) Typeface mType = TypefacecreateFromAsset( cgetAssets() fontsBaroqueScriptttf) Paint p =new Paint(PaintANTI_ALIAS_FLAG) psetTypeface(mType) psetTextSize(20) canvasdrawColor(ColorBLUE) canvasdrawText(Welcome to Android canvasgetWidth()4 canvasgetHeight()3 p)

SampleCustomFontjava package compritesh import androidappActivity import androidgraphicsTypeface import androidosBundle public class SampleCustomFont extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain) setContentView(new ViewFont(this))

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 20

Working with Bitmap and Matrix Bitmap

In computer graphics a bitmap or pixmap is a type of memory organization

or image file format used to store digital images The term bitmap comes from the

computer programming terminology meaning just a map of bits a spatially mapped array of bits Now along with pixmap it commonly refers to the similar

concept of a spatially mapped array of pixels Raster images in general may be referred to as bitmaps or pixmaps whether synthetic or photographic in files or

memory In certain contexts the term bitmap implies one bit per pixel while pixmap

is used for images with multiple bits per pixel

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 21

Shape Drawable in XML

This is a generic shape defined in XML

File location

resdrawablefilenamexml

The filename is used as the resource ID

Compiled resource datatype

Resource pointer to a GradientDrawable

Resource reference

In Java Rdrawablefilename

In XML [package]drawablefilename

Syntax

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=[rectangle | oval | line | ring] gt ltcorners androidradius=integer androidtopLeftRadius=integer androidtopRightRadius=integer androidbottomLeftRadius=integer androidbottomRightRadius=integer gt ltgradient androidangle=integer androidcenterX=integer androidcenterY=integer androidcenterColor=integer androidendColor=color androidgradientRadius=integer androidstartColor=color androidtype=[linear | radial | sweep] androidusesLevel=[true | false] gt ltpadding androidleft=integer androidtop=integer androidright=integer androidbottom=integer gt ltsize androidwidth=integer androidheight=integer gt ltsolid

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 22

androidcolor=color gt ltstroke androidwidth=integer androidcolor=color androiddashWidth=integer androiddashGap=integer gt ltshapegt

Elements

ltshapegt

The shape drawable This must be the root element

Attributes

xmlnsandroid

String Required Defines the XML namespace which must be

httpschemasandroidcomapkresandroid

androidshape

Keyword Defines the type of shape Valid values are

Value Desciption

rectangle A rectangle that fills the containing View This is the default shape

oval An oval shape that fits the dimensions of the containing View

line A horizontal line that spans the width of the containing View This

shape requires the ltstrokegt element to define the width of the line

ring A ring shape

The following attributes are used only when androidshape=ring

androidinnerRadius

Dimension The radius for the inner part of the ring (the hole in the middle)

as a dimension value or dimension resource

androidinnerRadiusRatio

Float The radius for the inner part of the ring expressed as a ratio of the

rings width For instance if androidinnerRadiusRatio=5 then the inner

radius equals the rings width divided by 5 This value is overridden by

androidinnerRadius Default value is 9

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 23

androidthickness

Dimension The thickness of the ring as a dimension value or dimension

resource

androidthicknessRatio

Float The thickness of the ring expressed as a ratio of the rings width For

instance if androidthicknessRatio=2 then the thickness equals the rings

width divided by 2 This value is overridden by androidinnerRadius Default

value is 3

androiduseLevel

Boolean true if this is used as a LevelListDrawable This should normally

be false or your shape may not appear

ltcornersgt

Creates rounded corners for the shape Applies only when the shape is a

rectangle

Attributes

androidradius

Dimension The radius for all corners as a dimension value or dimension

resource This is overridden for each corner by the following attributes

androidtopLeftRadius

Dimension The radius for the top-left corner as a dimension value or

dimension resource

androidtopRightRadius

Dimension The radius for the top-right corner as a dimension value or

dimension resource

androidbottomLeftRadius

Dimension The radius for the bottom-left corner as a dimension value or

dimension resource

androidbottomRightRadius

Dimension The radius for the bottom-right corner as a dimension value or

dimension resource

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 24

Note Every corner must (initially) be provided a corner radius greater than

1 or else no corners are rounded If you want specific corners to not be rounded a work-around is to use androidradius to set a default corner

radius greater than 1 but then override each and every corner with the values you really want providing zero (0dp) where you dont want rounded

corners

ltgradientgt

Specifies a gradient color for the shape

Attributes

androidangle

Integer The angle for the gradient in degrees 0 is left to right 90 is bottom

to top It must be a multiple of 45 Default is 0

androidcenterX

Float The relative X-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterY

Float The relative Y-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterColor

Color Optional color that comes between the start and end colors as a

hexadecimal value or color resource

androidendColor

Color The ending color as a hexadecimal value or color resource

androidgradientRadius

Float The radius for the gradient Only applied when androidtype=radial

androidstartColor

Color The starting color as a hexadecimal value or color resource

androidtype

Keyword The type of gradient pattern to apply Valid values are

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 25

Value Description

linear A linear gradient This is the default

radial A radial gradient The start color is the center color

sweep A sweeping line gradient

androiduseLevel

Boolean true if this is used as a LevelListDrawable

ltpaddinggt

Padding to apply to the containing View element (this pads the position of

the View content not the shape)

Attributes

androidleft

Dimension Left padding as a dimension value or dimension resource

androidtop

Dimension Top padding as a dimension value or dimension resource

androidright

Dimension Right padding as a dimension value or dimension resource

androidbottom

Dimension Bottom padding as a dimension value or dimension resource

ltsizegt

The size of the shape

Attributes

androidheight

Dimension The height of the shape as a dimension value or dimension

resource

androidwidth

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 26

Dimension The width of the shape as a dimension value or dimension

resource

Note The shape scales to the size of the container View proportionate to the

dimensions defined here by default When you use the shape in an ImageView you can restrict scaling by setting the androidscaleType to center

ltsolidgt

A solid color to fill the shape

Attributes

androidcolor

Color The color to apply to the shape as a hexadecimal value or color

resource

ltstrokegt

A stroke line for the shape

Attributes

androidwidth

Dimension The thickness of the line as a dimension value or dimension

resource

androidcolor

Color The color of the line as a hexadecimal value or color resource

androiddashGap

Dimension The distance between line dashes as a dimension value or

dimension resource Only valid if androiddashWidth is set

androiddashWidth

Dimension The size of each dash line as a dimension value or dimension

resource Only valid if androiddashGap is set

Example

XML file saved at resdrawablegradient_boxxml

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 27

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=rectanglegt ltgradient androidstartColor=FFFF0000 androidendColor=80FF00FF androidangle=45gt ltpadding androidleft=7dp androidtop=7dp androidright=7dp androidbottom=7dp gt ltcorners androidradius=8dp gt ltshapegt

This layout XML applies the shape drawable to a View

ltTextView androidbackground=drawablegradient_box androidlayout_height=wrap_content androidlayout_width=wrap_content gt

This application code gets the shape drawable and applies it to a View

Resources res = getResources() Drawable shape = res getDrawable(Rdrawablegradient_box)

TextView tv = (TextView)findViewByID(Ridtextview) tvsetBackground(shape)

Page 7: Android graphics mca 5th

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 7

ImageView image = (ImageView) findViewById(Ridtoggle_image)

imagesetImageDrawable(transition)

Then this transition can be run forward (for 1 second) with

transitionstartTransition(1000)

Canvas class

The Canvas class holds the draw calls To draw something you need 4 basic

components A Bitmap to hold the pixels a Canvas to host the draw calls (writing

into the bitmap) a drawing primitive (eg Rect Path text Bitmap) and a paint (to

describe the colors and styles for the drawing)

Public Constructors

Canvas() Construct an empty raster canvas

Canvas(Bitmap bitmap) Construct a canvas with the specified bitmap to draw into

Public Methods

void drawArc(RectF oval float startAngle float sweepAngle boolean useCenter Paint paint)

Draw the specified arc which will be scaled to fit inside the specified

oval

void drawBitmap(Bitmap bitmap float left float top Paint paint) Draw the specified bitmap with its topleft corner at (xy) using the

specified paint transformed by the current matrix

void drawCircle(float cx float cy float radius Paint paint) Draw the specified circle using the specified paint

void drawColor(int color) Fill the entire canvas bitmap (restricted to the current clip) with the specified color using srcover porterduff mode

void drawLine(float startX float startY float stopX float stopY Paint paint)

Draw a line segment with the specified start and stop xy coordinates using the specified paint

void drawLines(float[] pts Paint paint)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 8

void drawLines(float[] pts int offset int count Paint paint)

Draw a series of lines

void drawOval(RectF oval Paint paint)

Draw the specified oval using the specified paint

void drawPaint(Paint paint)

Fill the entire canvas bitmap (restricted to the current clip) with the specified paint

void drawPicture(Picture picture) Save the canvas state draw the picture and restore the canvas state

void drawPicture(Picture picture Rect dst) Draw the picture stretched to fit into the dst rectangle

void drawPoint(float x float y Paint paint) Helper for drawPoints() for drawing a single point

void drawPoints(float[] pts int offset int count Paint paint) Draw a series of points

void drawPoints(float[] pts Paint paint) Helper for drawPoints() that assumes you want to draw the entire

array

void drawPosText(char[] text int index int count float[] pos Paint paint)

Draw the text in the array with each characters origin specified by the pos array

void drawPosText(String text float[] pos Paint paint) Draw the text in the array with each characters origin specified by the pos array

void drawRGB(int r int g int b) Fill the entire canvas bitmap (restricted to the current clip) with the

specified RGB color using srcover porterduff mode

void drawRect(float left float top float right float bottom Paint paint)

Draw the specified Rect using the specified paint

void drawRect(RectF rect Paint paint)

Draw the specified Rect using the specified paint

void drawRect(Rect r Paint paint)

Draw the specified Rect using the specified Paint

void drawRoundRect(RectF rect float rx float ry Paint paint)

Draw the specified round-rect using the specified paint

void drawText(String text float x float y Paint paint)

Draw the text with origin at (xy) using the specified paint

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 9

void drawText(CharSequence text int start int end float x float

y Paint paint) Draw the specified range of text specified by startend with its origin at (xy) in the specified Paint

void drawText(char[] text int index int count float x float y Paint paint) Draw the text with origin at (xy) using the specified paint

void drawText(String text int start int end float x float y Paint paint) Draw the text with origin at (xy) using the specified paint

void drawTextOnPath(String text Path path float hOffset float vOffset Paint paint)

Draw the text with origin at (xy) using the specified paint along the specified path

void drawTextOnPath(char[] text int index int count Path path float hOffset float vOffset Paint paint)

Draw the text with origin at (xy) using the specified paint along the specified path

int getHeight() Returns the height of the current drawing layer

void getMatrix(Matrix ctm) Return in ctm the current transformation matrix

final Matrix

getMatrix() Return a new matrix with a copy of the canvas current transformation matrix

int getWidth() Returns the width of the current drawing layer

void rotate(float degrees) Preconcat the current matrix with the specified rotation

final void

rotate(float degrees float px float py) Preconcat the current matrix with the specified rotation

void scale(float sx float sy) Preconcat the current matrix with the specified scale

final

void scale(float sx float sy float px float py)

Preconcat the current matrix with the specified scale

void setBitmap(Bitmap bitmap)

Specify a bitmap for the canvas to draw into

void translate(float dx float dy)

Preconcat the current matrix with the specified translation

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 10

Paint class

The Paint class holds the style and color information about how to draw

geometries text and bitmaps

Paint Styles

public static final PaintStyle FILL

Geometry and text drawn with this style will be filled ignoring all stroke-related

settings in the paint

public static final PaintStyle FILL_AND_STROKE

Geometry and text drawn with this style will be both filled and stroked at the same time respecting the stroke-related fields on the paint This mode can give unexpected results if the geometry is oriented counter-clockwise This restriction

does not apply to either FILL or STROKE

public static final PaintStyle STROKE

Geometry and text drawn with this style will be stroked respecting the stroke-related fields on the paint

Public Constructors

Paint()

Create a new paint with default settings

Paint(int flags)

Create a new paint with the specified flags

Paint(Paint paint)

Create a new paint initialized with the attributes in the specified paint parameter

Public Methods

int getAlpha()

Helper to getColor() that just returns the colors alpha value

int getColor()

Return the paints color

ColorFilter getColorFilter()

Get the paints colorfilter (maybe be null)

boolean

getFillPath(Path src Path dst)

Applies anyall effects (patheffect stroking) to src returning

the result in dst

int getFlags()

Return the paints flags

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 11

PaintFontMetrics

getFontMetrics()

Allocates a new FontMetrics object and then calls

getFontMetrics(fm) with it returning the object

int

getFontMetricsInt(PaintFontMetricsInt fmi)

Return the fonts interline spacing given the Paints settings

for typeface textSize etc

float

getFontSpacing()

Return the recommend line spacing based on the current

typeface and text size

MaskFilter getMaskFilter()

Get the paints maskfilter object

Shader getShader()

Get the paints shader object

PaintStyle

getStyle()

Return the paints style used for controlling how primitives

geometries are interpreted (except for drawBitmap which

always assumes FILL_STYLE)

PaintAlign getTextAlign()

Return the paints Align value for drawing text

void

getTextBounds(char[] text int index int count Rect bounds)

Return in bounds (allocated by the caller) the smallest

rectangle that encloses all of the characters with an implied

origin at (00)

void

getTextBounds(String text int start int end Rect bounds)

Return in bounds (allocated by the caller) the smallest

rectangle that encloses all of the characters with an implied

origin at (00)

void

getTextPath(String text int start int end float x float y Path

path)

Return the path (outline) for the specified text

void

getTextPath(char[] text int index int count float x float y

Path path)

Return the path (outline) for the specified text

float getTextScaleX()

Return the paints horizontal scale factor for text

float getTextSize()

Return the paints text size

int getTextWidths(String text float[] widths)

Return the advance widths for the characters in the string

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 12

int

getTextWidths(CharSequence text int start int end float[]

widths)

Return the advance widths for the characters in the string

int getTextWidths(String text int start int end float[] widths)

Return the advance widths for the characters in the string

int getTextWidths(char[] text int index int count float[] widths)

Return the advance widths for the characters in the string

Typeface getTypeface()

Get the paints typeface object

final boolean

isAntiAlias()

Helper for getFlags() returning true if ANTI_ALIAS_FLAG bit is

set AntiAliasing smooths out the edges of what is being

drawn but is has no impact on the interior of the shape

final boolean

isStrikeThruText()

Helper for getFlags() returning true if

STRIKE_THRU_TEXT_FLAG bit is set

final boolean

isSubpixelText()

Helper for getFlags() returning true if SUBPIXEL_TEXT_FLAG

bit is set

final boolean

isUnderlineText()

Helper for getFlags() returning true if

UNDERLINE_TEXT_FLAG bit is set

float measureText(String text)

Return the width of the text

float measureText(CharSequence text int start int end)

Return the width of the text

float measureText(String text int start int end)

Return the width of the text

float measureText(char[] text int index int count)

Return the width of the text

void reset()

Restores the paint to its default settings

void set(Paint src)

Copy the fields from src into this paint

void

setARGB(int a int r int g int b)

Helper to setColor() that takes argb and constructs the

color int

void setAlpha(int a)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 13

Helper to setColor() that only assigns the colors alpha value

leaving its rgb values unchanged

void

setAntiAlias(boolean aa)

Helper for setFlags() setting or clearing the ANTI_ALIAS_FLAG

bit AntiAliasing smooths out the edges of what is being drawn

but is has no impact on the interior of the shape

void setColor(int color)

Set the paints color

ColorFilter setColorFilter(ColorFilter filter)

Set or clear the paints colorfilter returning the parameter

void

setFakeBoldText(boolean fakeBoldText)

Helper for setFlags() setting or clearing the

FAKE_BOLD_TEXT_FLAG bit

void setFlags(int flags)

Set the paints flags

PathEffect setPathEffect(PathEffect effect)

Set or clear the patheffect object

Shader setShader(Shader shader)

Set or clear the shader object

void

setShadowLayer(float radius float dx float dy int color)

This draws a shadow layer below the main layer with the

specified offset and color and blur radius

void

setStrikeThruText(boolean strikeThruText)

Helper for setFlags() setting or clearing the

STRIKE_THRU_TEXT_FLAG bit

void

setStyle(PaintStyle style)

Set the paints style used for controlling how primitives

geometries are interpreted (except for drawBitmap which

always assumes Fill)

void

setSubpixelText(boolean subpixelText)

Helper for setFlags() setting or clearing the

SUBPIXEL_TEXT_FLAG bit

void setTextAlign(PaintAlign align)

Set the paints text alignment

void setTextSize(float textSize)

Set the paints text size

void setTextSkewX(float skewX)

Set the paints horizontal skew factor for text

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 14

Typeface setTypeface(Typeface typeface)

Set or clear the typeface object

void

setUnderlineText(boolean underlineText)

Helper for setFlags() setting or clearing the

UNDERLINE_TEXT_FLAG bit

Types of Gradient

1 Linear Gradient

public LinearGradient (float x0 float y0 float x1 float y1 int[] colors float[]

positions ShaderTileMode tile)

Create a shader that draws a linear gradient along a line

Parameters

x0 The x-coordinate for the start of the gradient line

y0 The y-coordinate for the start of the gradient line

x1 The x-coordinate for the end of the gradient line

y1 The y-coordinate for the end of the gradient line

colors The colors to be distributed along the gradient line

positions

May be null The relative positions [01] of each corresponding color in

the colors array If this is null the the colors are distributed evenly

along the gradient line

tile The Shader tiling mode

2 Sweep Gradient

public SweepGradient (float cx float cy int[] colors float[] positions)

A subclass of Shader that draws a sweep gradient around a center point

Parameters

cx The x-coordinate of the center

cy The y-coordinate of the center

colors The colors to be distributed between around the center There must be

at least 2 colors in the array

positions

May be NULL The relative position of each corresponding color in the

colors array beginning with 0 and ending with 10 If the values are not

monotonic the drawing may produce unexpected results If positions is

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 15

NULL then the colors are automatically spaced evenly

3 Radial Gradient

public RadialGradient (float x float y float radius int[] colors float[] positions

ShaderTileMode tile)

Create a shader that draws a radial gradient given the center and radius

Parameters

x The x-coordinate of the center of the radius

y The y-coordinate of the center of the radius

radius Must be positive The radius of the circle for this gradient

colors The colors to be distributed between the center and edge of the circle

positions

May be NULL The relative position of each corresponding color in the

colors array If this is NULL the the colors are distributed evenly

between the center and edge of the circle

tile The Shader tiling mode

Shader Class

Shader is the based class for objects that return horizontal spans of colors during

drawing A subclass of Shader is installed in a Paint calling

paintsetShader(shader) After that any object (other than a bitmap) that is drawn

with that paint will get its color(s) from the shader

ShaderTileMode CLAMP replicate the edge color if the shader draws

outside of its original bounds

ShaderTileMode MIRROR repeat the shaders image horizontally and

vertically alternating mirror images so that adjacent images always seam

ShaderTileMode REPEAT repeat the shaders image horizontally and

vertically

Color

The Color class defines methods for creating and converting color ints Colors are

represented as packed ints made up of 4 bytes alpha red green blue The

values are unpremultiplied meaning any transparency is stored solely in the

alpha component and not in the color components The components are stored as

follows (alpha ltlt 24) | (red ltlt 16) | (green ltlt 8) | blue Each component ranges

between 0255 with 0 meaning no contribution for that component and 255

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 16

meaning 100 contribution Thus opaque-black would be 0xFF000000 (100

opaque but no contributions from red green or blue) and opaque-white would be

0xFFFFFFFF

Constant

int BLACK int LTGRAY

int BLUE int MAGENTA

int CYAN int RED

int DKGRAY int TRANSPARENT

int GRAY int WHITE

int GREEN int YELLOW

Public Constructors

Color()

Public Methods

static int HSVToColor(float[] hsv)

Convert HSV components to an ARGB color

static int HSVToColor(int alpha float[] hsv)

Convert HSV components to an ARGB color

static void RGBToHSV(int red int green int blue float[] hsv)

Convert RGB components to HSV

static int alpha(int color)

Return the alpha component of a color int

static int argb(int alpha int red int green int blue)

Return a color-int from alpha red green blue components

static int blue(int color)

Return the blue component of a color int

static void colorToHSV(int color float[] hsv)

Convert the argb color to its HSV components

static int green(int color)

Return the green component of a color int

static int parseColor(String colorString)

Parse the color string and return the corresponding color-int

static int red(int color)

Return the red component of a color int

static int rgb(int red int green int blue)

Return a color-int from red green blue components

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 17

Working with Text

Android provide several default fonts typeface and styles Application can also use

custom fonts by including font files as application assets and loading them using

the AssetManger same as recourses

Typeface class

The Typeface class specifies the typeface and intrinsic style of a font This is used

in the paint along with optionally Paint settings like textSize textSkewX

textScaleX to specify how text appears when drawn (and measured)

Constant

int BOLD

int BOLD_ITALIC

int ITALIC

int NORMAL

Fields

public static

final Typeface DEFAULT The default NORMAL typeface object

public static

final Typeface DEFAULT_BOLD The default BOLD typeface object

public static

final Typeface MONOSPACE The NORMAL style of the default monospace typeface

public static

final Typeface SANS_SERIF The NORMAL style of the default sans serif typeface

public static

final Typeface SERIF The NORMAL style of the default serif typeface

Public Methods

static

Typeface

create(String familyName int style)

Create a typeface object given a family name and option style

information

static

Typeface

create(Typeface family int style)

Create a typeface object that best matches the specified existing typeface

and the specified Style

static

Typeface

createFromAsset(AssetManager mgr String path)

Create a new typeface from the specified font data

static

Typeface

createFromFile(String path)

Create a new typeface from the specified font file

static createFromFile(File path)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 18

Typeface Create a new typeface from the specified font file

static

Typeface

defaultFromStyle(int style)

Returns one of the default typeface objects based on the specified style

int getStyle()

Returns the typefaces intrinsic style attributes

final

boolean

isBold()

Returns true if getStyle() has the BOLD bit set

final

boolean

isItalic()

Returns true if getStyle() has the ITALIC bit set

Using Default Fonts and Typefaces

By default Android uses the Sans Serif typeface but Monospace and Serif

typefaces are also available The following code excerpt draws some antialiased text in the default typeface (Sans Serif) to a Canvas

import androidgraphicsCanvas import androidgraphicsColor import androidgraphicsPaint import androidgraphicsTypeface Paint mPaint = new Paint(PaintANTI_ALIAS_FLAG) Typeface mType mPaintsetTextSize(16) mPaintsetTypeface(null) canvasdrawText(ldquoDefault Typefacerdquo 20 20 mPaint) You can instead load a different typeface such as Monotype

Typeface mType = Typefacecreate(TypefaceMONOSPACE TypefaceNORMAL) Perhaps you would prefer italic text in which case you can simply set the style of the typeface and the font family

Typeface mType = Typefacecreate(TypefaceSERIF TypefaceITALIC)

You can set certain properties of a typeface such as antialiasing underlining and strikethrough using the setFlags() method of the Paint object

mPaintsetFlags(PaintUNDERLINE_TEXT_FLAG)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 19

Loading Custom typeface from asset

Typeface mType = TypefacecreateFromAsset(getContext()getAssets()ldquofontschess1ttfrdquo) Example ViewFontjava

package compritesh

import androidcontentContext import androidgraphicsCanvas import androidgraphicsColor import androidgraphicsPaint import androidgraphicsTypeface import androidviewView public class ViewFont extends View Context c public ViewFont(Context context) super(context) c=context protected void onDraw(Canvas canvas) Typeface mType = TypefacecreateFromAsset( cgetAssets() fontsBaroqueScriptttf) Paint p =new Paint(PaintANTI_ALIAS_FLAG) psetTypeface(mType) psetTextSize(20) canvasdrawColor(ColorBLUE) canvasdrawText(Welcome to Android canvasgetWidth()4 canvasgetHeight()3 p)

SampleCustomFontjava package compritesh import androidappActivity import androidgraphicsTypeface import androidosBundle public class SampleCustomFont extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain) setContentView(new ViewFont(this))

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 20

Working with Bitmap and Matrix Bitmap

In computer graphics a bitmap or pixmap is a type of memory organization

or image file format used to store digital images The term bitmap comes from the

computer programming terminology meaning just a map of bits a spatially mapped array of bits Now along with pixmap it commonly refers to the similar

concept of a spatially mapped array of pixels Raster images in general may be referred to as bitmaps or pixmaps whether synthetic or photographic in files or

memory In certain contexts the term bitmap implies one bit per pixel while pixmap

is used for images with multiple bits per pixel

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 21

Shape Drawable in XML

This is a generic shape defined in XML

File location

resdrawablefilenamexml

The filename is used as the resource ID

Compiled resource datatype

Resource pointer to a GradientDrawable

Resource reference

In Java Rdrawablefilename

In XML [package]drawablefilename

Syntax

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=[rectangle | oval | line | ring] gt ltcorners androidradius=integer androidtopLeftRadius=integer androidtopRightRadius=integer androidbottomLeftRadius=integer androidbottomRightRadius=integer gt ltgradient androidangle=integer androidcenterX=integer androidcenterY=integer androidcenterColor=integer androidendColor=color androidgradientRadius=integer androidstartColor=color androidtype=[linear | radial | sweep] androidusesLevel=[true | false] gt ltpadding androidleft=integer androidtop=integer androidright=integer androidbottom=integer gt ltsize androidwidth=integer androidheight=integer gt ltsolid

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 22

androidcolor=color gt ltstroke androidwidth=integer androidcolor=color androiddashWidth=integer androiddashGap=integer gt ltshapegt

Elements

ltshapegt

The shape drawable This must be the root element

Attributes

xmlnsandroid

String Required Defines the XML namespace which must be

httpschemasandroidcomapkresandroid

androidshape

Keyword Defines the type of shape Valid values are

Value Desciption

rectangle A rectangle that fills the containing View This is the default shape

oval An oval shape that fits the dimensions of the containing View

line A horizontal line that spans the width of the containing View This

shape requires the ltstrokegt element to define the width of the line

ring A ring shape

The following attributes are used only when androidshape=ring

androidinnerRadius

Dimension The radius for the inner part of the ring (the hole in the middle)

as a dimension value or dimension resource

androidinnerRadiusRatio

Float The radius for the inner part of the ring expressed as a ratio of the

rings width For instance if androidinnerRadiusRatio=5 then the inner

radius equals the rings width divided by 5 This value is overridden by

androidinnerRadius Default value is 9

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 23

androidthickness

Dimension The thickness of the ring as a dimension value or dimension

resource

androidthicknessRatio

Float The thickness of the ring expressed as a ratio of the rings width For

instance if androidthicknessRatio=2 then the thickness equals the rings

width divided by 2 This value is overridden by androidinnerRadius Default

value is 3

androiduseLevel

Boolean true if this is used as a LevelListDrawable This should normally

be false or your shape may not appear

ltcornersgt

Creates rounded corners for the shape Applies only when the shape is a

rectangle

Attributes

androidradius

Dimension The radius for all corners as a dimension value or dimension

resource This is overridden for each corner by the following attributes

androidtopLeftRadius

Dimension The radius for the top-left corner as a dimension value or

dimension resource

androidtopRightRadius

Dimension The radius for the top-right corner as a dimension value or

dimension resource

androidbottomLeftRadius

Dimension The radius for the bottom-left corner as a dimension value or

dimension resource

androidbottomRightRadius

Dimension The radius for the bottom-right corner as a dimension value or

dimension resource

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 24

Note Every corner must (initially) be provided a corner radius greater than

1 or else no corners are rounded If you want specific corners to not be rounded a work-around is to use androidradius to set a default corner

radius greater than 1 but then override each and every corner with the values you really want providing zero (0dp) where you dont want rounded

corners

ltgradientgt

Specifies a gradient color for the shape

Attributes

androidangle

Integer The angle for the gradient in degrees 0 is left to right 90 is bottom

to top It must be a multiple of 45 Default is 0

androidcenterX

Float The relative X-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterY

Float The relative Y-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterColor

Color Optional color that comes between the start and end colors as a

hexadecimal value or color resource

androidendColor

Color The ending color as a hexadecimal value or color resource

androidgradientRadius

Float The radius for the gradient Only applied when androidtype=radial

androidstartColor

Color The starting color as a hexadecimal value or color resource

androidtype

Keyword The type of gradient pattern to apply Valid values are

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 25

Value Description

linear A linear gradient This is the default

radial A radial gradient The start color is the center color

sweep A sweeping line gradient

androiduseLevel

Boolean true if this is used as a LevelListDrawable

ltpaddinggt

Padding to apply to the containing View element (this pads the position of

the View content not the shape)

Attributes

androidleft

Dimension Left padding as a dimension value or dimension resource

androidtop

Dimension Top padding as a dimension value or dimension resource

androidright

Dimension Right padding as a dimension value or dimension resource

androidbottom

Dimension Bottom padding as a dimension value or dimension resource

ltsizegt

The size of the shape

Attributes

androidheight

Dimension The height of the shape as a dimension value or dimension

resource

androidwidth

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 26

Dimension The width of the shape as a dimension value or dimension

resource

Note The shape scales to the size of the container View proportionate to the

dimensions defined here by default When you use the shape in an ImageView you can restrict scaling by setting the androidscaleType to center

ltsolidgt

A solid color to fill the shape

Attributes

androidcolor

Color The color to apply to the shape as a hexadecimal value or color

resource

ltstrokegt

A stroke line for the shape

Attributes

androidwidth

Dimension The thickness of the line as a dimension value or dimension

resource

androidcolor

Color The color of the line as a hexadecimal value or color resource

androiddashGap

Dimension The distance between line dashes as a dimension value or

dimension resource Only valid if androiddashWidth is set

androiddashWidth

Dimension The size of each dash line as a dimension value or dimension

resource Only valid if androiddashGap is set

Example

XML file saved at resdrawablegradient_boxxml

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 27

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=rectanglegt ltgradient androidstartColor=FFFF0000 androidendColor=80FF00FF androidangle=45gt ltpadding androidleft=7dp androidtop=7dp androidright=7dp androidbottom=7dp gt ltcorners androidradius=8dp gt ltshapegt

This layout XML applies the shape drawable to a View

ltTextView androidbackground=drawablegradient_box androidlayout_height=wrap_content androidlayout_width=wrap_content gt

This application code gets the shape drawable and applies it to a View

Resources res = getResources() Drawable shape = res getDrawable(Rdrawablegradient_box)

TextView tv = (TextView)findViewByID(Ridtextview) tvsetBackground(shape)

Page 8: Android graphics mca 5th

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 8

void drawLines(float[] pts int offset int count Paint paint)

Draw a series of lines

void drawOval(RectF oval Paint paint)

Draw the specified oval using the specified paint

void drawPaint(Paint paint)

Fill the entire canvas bitmap (restricted to the current clip) with the specified paint

void drawPicture(Picture picture) Save the canvas state draw the picture and restore the canvas state

void drawPicture(Picture picture Rect dst) Draw the picture stretched to fit into the dst rectangle

void drawPoint(float x float y Paint paint) Helper for drawPoints() for drawing a single point

void drawPoints(float[] pts int offset int count Paint paint) Draw a series of points

void drawPoints(float[] pts Paint paint) Helper for drawPoints() that assumes you want to draw the entire

array

void drawPosText(char[] text int index int count float[] pos Paint paint)

Draw the text in the array with each characters origin specified by the pos array

void drawPosText(String text float[] pos Paint paint) Draw the text in the array with each characters origin specified by the pos array

void drawRGB(int r int g int b) Fill the entire canvas bitmap (restricted to the current clip) with the

specified RGB color using srcover porterduff mode

void drawRect(float left float top float right float bottom Paint paint)

Draw the specified Rect using the specified paint

void drawRect(RectF rect Paint paint)

Draw the specified Rect using the specified paint

void drawRect(Rect r Paint paint)

Draw the specified Rect using the specified Paint

void drawRoundRect(RectF rect float rx float ry Paint paint)

Draw the specified round-rect using the specified paint

void drawText(String text float x float y Paint paint)

Draw the text with origin at (xy) using the specified paint

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 9

void drawText(CharSequence text int start int end float x float

y Paint paint) Draw the specified range of text specified by startend with its origin at (xy) in the specified Paint

void drawText(char[] text int index int count float x float y Paint paint) Draw the text with origin at (xy) using the specified paint

void drawText(String text int start int end float x float y Paint paint) Draw the text with origin at (xy) using the specified paint

void drawTextOnPath(String text Path path float hOffset float vOffset Paint paint)

Draw the text with origin at (xy) using the specified paint along the specified path

void drawTextOnPath(char[] text int index int count Path path float hOffset float vOffset Paint paint)

Draw the text with origin at (xy) using the specified paint along the specified path

int getHeight() Returns the height of the current drawing layer

void getMatrix(Matrix ctm) Return in ctm the current transformation matrix

final Matrix

getMatrix() Return a new matrix with a copy of the canvas current transformation matrix

int getWidth() Returns the width of the current drawing layer

void rotate(float degrees) Preconcat the current matrix with the specified rotation

final void

rotate(float degrees float px float py) Preconcat the current matrix with the specified rotation

void scale(float sx float sy) Preconcat the current matrix with the specified scale

final

void scale(float sx float sy float px float py)

Preconcat the current matrix with the specified scale

void setBitmap(Bitmap bitmap)

Specify a bitmap for the canvas to draw into

void translate(float dx float dy)

Preconcat the current matrix with the specified translation

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 10

Paint class

The Paint class holds the style and color information about how to draw

geometries text and bitmaps

Paint Styles

public static final PaintStyle FILL

Geometry and text drawn with this style will be filled ignoring all stroke-related

settings in the paint

public static final PaintStyle FILL_AND_STROKE

Geometry and text drawn with this style will be both filled and stroked at the same time respecting the stroke-related fields on the paint This mode can give unexpected results if the geometry is oriented counter-clockwise This restriction

does not apply to either FILL or STROKE

public static final PaintStyle STROKE

Geometry and text drawn with this style will be stroked respecting the stroke-related fields on the paint

Public Constructors

Paint()

Create a new paint with default settings

Paint(int flags)

Create a new paint with the specified flags

Paint(Paint paint)

Create a new paint initialized with the attributes in the specified paint parameter

Public Methods

int getAlpha()

Helper to getColor() that just returns the colors alpha value

int getColor()

Return the paints color

ColorFilter getColorFilter()

Get the paints colorfilter (maybe be null)

boolean

getFillPath(Path src Path dst)

Applies anyall effects (patheffect stroking) to src returning

the result in dst

int getFlags()

Return the paints flags

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 11

PaintFontMetrics

getFontMetrics()

Allocates a new FontMetrics object and then calls

getFontMetrics(fm) with it returning the object

int

getFontMetricsInt(PaintFontMetricsInt fmi)

Return the fonts interline spacing given the Paints settings

for typeface textSize etc

float

getFontSpacing()

Return the recommend line spacing based on the current

typeface and text size

MaskFilter getMaskFilter()

Get the paints maskfilter object

Shader getShader()

Get the paints shader object

PaintStyle

getStyle()

Return the paints style used for controlling how primitives

geometries are interpreted (except for drawBitmap which

always assumes FILL_STYLE)

PaintAlign getTextAlign()

Return the paints Align value for drawing text

void

getTextBounds(char[] text int index int count Rect bounds)

Return in bounds (allocated by the caller) the smallest

rectangle that encloses all of the characters with an implied

origin at (00)

void

getTextBounds(String text int start int end Rect bounds)

Return in bounds (allocated by the caller) the smallest

rectangle that encloses all of the characters with an implied

origin at (00)

void

getTextPath(String text int start int end float x float y Path

path)

Return the path (outline) for the specified text

void

getTextPath(char[] text int index int count float x float y

Path path)

Return the path (outline) for the specified text

float getTextScaleX()

Return the paints horizontal scale factor for text

float getTextSize()

Return the paints text size

int getTextWidths(String text float[] widths)

Return the advance widths for the characters in the string

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 12

int

getTextWidths(CharSequence text int start int end float[]

widths)

Return the advance widths for the characters in the string

int getTextWidths(String text int start int end float[] widths)

Return the advance widths for the characters in the string

int getTextWidths(char[] text int index int count float[] widths)

Return the advance widths for the characters in the string

Typeface getTypeface()

Get the paints typeface object

final boolean

isAntiAlias()

Helper for getFlags() returning true if ANTI_ALIAS_FLAG bit is

set AntiAliasing smooths out the edges of what is being

drawn but is has no impact on the interior of the shape

final boolean

isStrikeThruText()

Helper for getFlags() returning true if

STRIKE_THRU_TEXT_FLAG bit is set

final boolean

isSubpixelText()

Helper for getFlags() returning true if SUBPIXEL_TEXT_FLAG

bit is set

final boolean

isUnderlineText()

Helper for getFlags() returning true if

UNDERLINE_TEXT_FLAG bit is set

float measureText(String text)

Return the width of the text

float measureText(CharSequence text int start int end)

Return the width of the text

float measureText(String text int start int end)

Return the width of the text

float measureText(char[] text int index int count)

Return the width of the text

void reset()

Restores the paint to its default settings

void set(Paint src)

Copy the fields from src into this paint

void

setARGB(int a int r int g int b)

Helper to setColor() that takes argb and constructs the

color int

void setAlpha(int a)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 13

Helper to setColor() that only assigns the colors alpha value

leaving its rgb values unchanged

void

setAntiAlias(boolean aa)

Helper for setFlags() setting or clearing the ANTI_ALIAS_FLAG

bit AntiAliasing smooths out the edges of what is being drawn

but is has no impact on the interior of the shape

void setColor(int color)

Set the paints color

ColorFilter setColorFilter(ColorFilter filter)

Set or clear the paints colorfilter returning the parameter

void

setFakeBoldText(boolean fakeBoldText)

Helper for setFlags() setting or clearing the

FAKE_BOLD_TEXT_FLAG bit

void setFlags(int flags)

Set the paints flags

PathEffect setPathEffect(PathEffect effect)

Set or clear the patheffect object

Shader setShader(Shader shader)

Set or clear the shader object

void

setShadowLayer(float radius float dx float dy int color)

This draws a shadow layer below the main layer with the

specified offset and color and blur radius

void

setStrikeThruText(boolean strikeThruText)

Helper for setFlags() setting or clearing the

STRIKE_THRU_TEXT_FLAG bit

void

setStyle(PaintStyle style)

Set the paints style used for controlling how primitives

geometries are interpreted (except for drawBitmap which

always assumes Fill)

void

setSubpixelText(boolean subpixelText)

Helper for setFlags() setting or clearing the

SUBPIXEL_TEXT_FLAG bit

void setTextAlign(PaintAlign align)

Set the paints text alignment

void setTextSize(float textSize)

Set the paints text size

void setTextSkewX(float skewX)

Set the paints horizontal skew factor for text

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 14

Typeface setTypeface(Typeface typeface)

Set or clear the typeface object

void

setUnderlineText(boolean underlineText)

Helper for setFlags() setting or clearing the

UNDERLINE_TEXT_FLAG bit

Types of Gradient

1 Linear Gradient

public LinearGradient (float x0 float y0 float x1 float y1 int[] colors float[]

positions ShaderTileMode tile)

Create a shader that draws a linear gradient along a line

Parameters

x0 The x-coordinate for the start of the gradient line

y0 The y-coordinate for the start of the gradient line

x1 The x-coordinate for the end of the gradient line

y1 The y-coordinate for the end of the gradient line

colors The colors to be distributed along the gradient line

positions

May be null The relative positions [01] of each corresponding color in

the colors array If this is null the the colors are distributed evenly

along the gradient line

tile The Shader tiling mode

2 Sweep Gradient

public SweepGradient (float cx float cy int[] colors float[] positions)

A subclass of Shader that draws a sweep gradient around a center point

Parameters

cx The x-coordinate of the center

cy The y-coordinate of the center

colors The colors to be distributed between around the center There must be

at least 2 colors in the array

positions

May be NULL The relative position of each corresponding color in the

colors array beginning with 0 and ending with 10 If the values are not

monotonic the drawing may produce unexpected results If positions is

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 15

NULL then the colors are automatically spaced evenly

3 Radial Gradient

public RadialGradient (float x float y float radius int[] colors float[] positions

ShaderTileMode tile)

Create a shader that draws a radial gradient given the center and radius

Parameters

x The x-coordinate of the center of the radius

y The y-coordinate of the center of the radius

radius Must be positive The radius of the circle for this gradient

colors The colors to be distributed between the center and edge of the circle

positions

May be NULL The relative position of each corresponding color in the

colors array If this is NULL the the colors are distributed evenly

between the center and edge of the circle

tile The Shader tiling mode

Shader Class

Shader is the based class for objects that return horizontal spans of colors during

drawing A subclass of Shader is installed in a Paint calling

paintsetShader(shader) After that any object (other than a bitmap) that is drawn

with that paint will get its color(s) from the shader

ShaderTileMode CLAMP replicate the edge color if the shader draws

outside of its original bounds

ShaderTileMode MIRROR repeat the shaders image horizontally and

vertically alternating mirror images so that adjacent images always seam

ShaderTileMode REPEAT repeat the shaders image horizontally and

vertically

Color

The Color class defines methods for creating and converting color ints Colors are

represented as packed ints made up of 4 bytes alpha red green blue The

values are unpremultiplied meaning any transparency is stored solely in the

alpha component and not in the color components The components are stored as

follows (alpha ltlt 24) | (red ltlt 16) | (green ltlt 8) | blue Each component ranges

between 0255 with 0 meaning no contribution for that component and 255

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 16

meaning 100 contribution Thus opaque-black would be 0xFF000000 (100

opaque but no contributions from red green or blue) and opaque-white would be

0xFFFFFFFF

Constant

int BLACK int LTGRAY

int BLUE int MAGENTA

int CYAN int RED

int DKGRAY int TRANSPARENT

int GRAY int WHITE

int GREEN int YELLOW

Public Constructors

Color()

Public Methods

static int HSVToColor(float[] hsv)

Convert HSV components to an ARGB color

static int HSVToColor(int alpha float[] hsv)

Convert HSV components to an ARGB color

static void RGBToHSV(int red int green int blue float[] hsv)

Convert RGB components to HSV

static int alpha(int color)

Return the alpha component of a color int

static int argb(int alpha int red int green int blue)

Return a color-int from alpha red green blue components

static int blue(int color)

Return the blue component of a color int

static void colorToHSV(int color float[] hsv)

Convert the argb color to its HSV components

static int green(int color)

Return the green component of a color int

static int parseColor(String colorString)

Parse the color string and return the corresponding color-int

static int red(int color)

Return the red component of a color int

static int rgb(int red int green int blue)

Return a color-int from red green blue components

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 17

Working with Text

Android provide several default fonts typeface and styles Application can also use

custom fonts by including font files as application assets and loading them using

the AssetManger same as recourses

Typeface class

The Typeface class specifies the typeface and intrinsic style of a font This is used

in the paint along with optionally Paint settings like textSize textSkewX

textScaleX to specify how text appears when drawn (and measured)

Constant

int BOLD

int BOLD_ITALIC

int ITALIC

int NORMAL

Fields

public static

final Typeface DEFAULT The default NORMAL typeface object

public static

final Typeface DEFAULT_BOLD The default BOLD typeface object

public static

final Typeface MONOSPACE The NORMAL style of the default monospace typeface

public static

final Typeface SANS_SERIF The NORMAL style of the default sans serif typeface

public static

final Typeface SERIF The NORMAL style of the default serif typeface

Public Methods

static

Typeface

create(String familyName int style)

Create a typeface object given a family name and option style

information

static

Typeface

create(Typeface family int style)

Create a typeface object that best matches the specified existing typeface

and the specified Style

static

Typeface

createFromAsset(AssetManager mgr String path)

Create a new typeface from the specified font data

static

Typeface

createFromFile(String path)

Create a new typeface from the specified font file

static createFromFile(File path)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 18

Typeface Create a new typeface from the specified font file

static

Typeface

defaultFromStyle(int style)

Returns one of the default typeface objects based on the specified style

int getStyle()

Returns the typefaces intrinsic style attributes

final

boolean

isBold()

Returns true if getStyle() has the BOLD bit set

final

boolean

isItalic()

Returns true if getStyle() has the ITALIC bit set

Using Default Fonts and Typefaces

By default Android uses the Sans Serif typeface but Monospace and Serif

typefaces are also available The following code excerpt draws some antialiased text in the default typeface (Sans Serif) to a Canvas

import androidgraphicsCanvas import androidgraphicsColor import androidgraphicsPaint import androidgraphicsTypeface Paint mPaint = new Paint(PaintANTI_ALIAS_FLAG) Typeface mType mPaintsetTextSize(16) mPaintsetTypeface(null) canvasdrawText(ldquoDefault Typefacerdquo 20 20 mPaint) You can instead load a different typeface such as Monotype

Typeface mType = Typefacecreate(TypefaceMONOSPACE TypefaceNORMAL) Perhaps you would prefer italic text in which case you can simply set the style of the typeface and the font family

Typeface mType = Typefacecreate(TypefaceSERIF TypefaceITALIC)

You can set certain properties of a typeface such as antialiasing underlining and strikethrough using the setFlags() method of the Paint object

mPaintsetFlags(PaintUNDERLINE_TEXT_FLAG)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 19

Loading Custom typeface from asset

Typeface mType = TypefacecreateFromAsset(getContext()getAssets()ldquofontschess1ttfrdquo) Example ViewFontjava

package compritesh

import androidcontentContext import androidgraphicsCanvas import androidgraphicsColor import androidgraphicsPaint import androidgraphicsTypeface import androidviewView public class ViewFont extends View Context c public ViewFont(Context context) super(context) c=context protected void onDraw(Canvas canvas) Typeface mType = TypefacecreateFromAsset( cgetAssets() fontsBaroqueScriptttf) Paint p =new Paint(PaintANTI_ALIAS_FLAG) psetTypeface(mType) psetTextSize(20) canvasdrawColor(ColorBLUE) canvasdrawText(Welcome to Android canvasgetWidth()4 canvasgetHeight()3 p)

SampleCustomFontjava package compritesh import androidappActivity import androidgraphicsTypeface import androidosBundle public class SampleCustomFont extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain) setContentView(new ViewFont(this))

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 20

Working with Bitmap and Matrix Bitmap

In computer graphics a bitmap or pixmap is a type of memory organization

or image file format used to store digital images The term bitmap comes from the

computer programming terminology meaning just a map of bits a spatially mapped array of bits Now along with pixmap it commonly refers to the similar

concept of a spatially mapped array of pixels Raster images in general may be referred to as bitmaps or pixmaps whether synthetic or photographic in files or

memory In certain contexts the term bitmap implies one bit per pixel while pixmap

is used for images with multiple bits per pixel

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 21

Shape Drawable in XML

This is a generic shape defined in XML

File location

resdrawablefilenamexml

The filename is used as the resource ID

Compiled resource datatype

Resource pointer to a GradientDrawable

Resource reference

In Java Rdrawablefilename

In XML [package]drawablefilename

Syntax

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=[rectangle | oval | line | ring] gt ltcorners androidradius=integer androidtopLeftRadius=integer androidtopRightRadius=integer androidbottomLeftRadius=integer androidbottomRightRadius=integer gt ltgradient androidangle=integer androidcenterX=integer androidcenterY=integer androidcenterColor=integer androidendColor=color androidgradientRadius=integer androidstartColor=color androidtype=[linear | radial | sweep] androidusesLevel=[true | false] gt ltpadding androidleft=integer androidtop=integer androidright=integer androidbottom=integer gt ltsize androidwidth=integer androidheight=integer gt ltsolid

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 22

androidcolor=color gt ltstroke androidwidth=integer androidcolor=color androiddashWidth=integer androiddashGap=integer gt ltshapegt

Elements

ltshapegt

The shape drawable This must be the root element

Attributes

xmlnsandroid

String Required Defines the XML namespace which must be

httpschemasandroidcomapkresandroid

androidshape

Keyword Defines the type of shape Valid values are

Value Desciption

rectangle A rectangle that fills the containing View This is the default shape

oval An oval shape that fits the dimensions of the containing View

line A horizontal line that spans the width of the containing View This

shape requires the ltstrokegt element to define the width of the line

ring A ring shape

The following attributes are used only when androidshape=ring

androidinnerRadius

Dimension The radius for the inner part of the ring (the hole in the middle)

as a dimension value or dimension resource

androidinnerRadiusRatio

Float The radius for the inner part of the ring expressed as a ratio of the

rings width For instance if androidinnerRadiusRatio=5 then the inner

radius equals the rings width divided by 5 This value is overridden by

androidinnerRadius Default value is 9

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 23

androidthickness

Dimension The thickness of the ring as a dimension value or dimension

resource

androidthicknessRatio

Float The thickness of the ring expressed as a ratio of the rings width For

instance if androidthicknessRatio=2 then the thickness equals the rings

width divided by 2 This value is overridden by androidinnerRadius Default

value is 3

androiduseLevel

Boolean true if this is used as a LevelListDrawable This should normally

be false or your shape may not appear

ltcornersgt

Creates rounded corners for the shape Applies only when the shape is a

rectangle

Attributes

androidradius

Dimension The radius for all corners as a dimension value or dimension

resource This is overridden for each corner by the following attributes

androidtopLeftRadius

Dimension The radius for the top-left corner as a dimension value or

dimension resource

androidtopRightRadius

Dimension The radius for the top-right corner as a dimension value or

dimension resource

androidbottomLeftRadius

Dimension The radius for the bottom-left corner as a dimension value or

dimension resource

androidbottomRightRadius

Dimension The radius for the bottom-right corner as a dimension value or

dimension resource

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 24

Note Every corner must (initially) be provided a corner radius greater than

1 or else no corners are rounded If you want specific corners to not be rounded a work-around is to use androidradius to set a default corner

radius greater than 1 but then override each and every corner with the values you really want providing zero (0dp) where you dont want rounded

corners

ltgradientgt

Specifies a gradient color for the shape

Attributes

androidangle

Integer The angle for the gradient in degrees 0 is left to right 90 is bottom

to top It must be a multiple of 45 Default is 0

androidcenterX

Float The relative X-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterY

Float The relative Y-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterColor

Color Optional color that comes between the start and end colors as a

hexadecimal value or color resource

androidendColor

Color The ending color as a hexadecimal value or color resource

androidgradientRadius

Float The radius for the gradient Only applied when androidtype=radial

androidstartColor

Color The starting color as a hexadecimal value or color resource

androidtype

Keyword The type of gradient pattern to apply Valid values are

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 25

Value Description

linear A linear gradient This is the default

radial A radial gradient The start color is the center color

sweep A sweeping line gradient

androiduseLevel

Boolean true if this is used as a LevelListDrawable

ltpaddinggt

Padding to apply to the containing View element (this pads the position of

the View content not the shape)

Attributes

androidleft

Dimension Left padding as a dimension value or dimension resource

androidtop

Dimension Top padding as a dimension value or dimension resource

androidright

Dimension Right padding as a dimension value or dimension resource

androidbottom

Dimension Bottom padding as a dimension value or dimension resource

ltsizegt

The size of the shape

Attributes

androidheight

Dimension The height of the shape as a dimension value or dimension

resource

androidwidth

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 26

Dimension The width of the shape as a dimension value or dimension

resource

Note The shape scales to the size of the container View proportionate to the

dimensions defined here by default When you use the shape in an ImageView you can restrict scaling by setting the androidscaleType to center

ltsolidgt

A solid color to fill the shape

Attributes

androidcolor

Color The color to apply to the shape as a hexadecimal value or color

resource

ltstrokegt

A stroke line for the shape

Attributes

androidwidth

Dimension The thickness of the line as a dimension value or dimension

resource

androidcolor

Color The color of the line as a hexadecimal value or color resource

androiddashGap

Dimension The distance between line dashes as a dimension value or

dimension resource Only valid if androiddashWidth is set

androiddashWidth

Dimension The size of each dash line as a dimension value or dimension

resource Only valid if androiddashGap is set

Example

XML file saved at resdrawablegradient_boxxml

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 27

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=rectanglegt ltgradient androidstartColor=FFFF0000 androidendColor=80FF00FF androidangle=45gt ltpadding androidleft=7dp androidtop=7dp androidright=7dp androidbottom=7dp gt ltcorners androidradius=8dp gt ltshapegt

This layout XML applies the shape drawable to a View

ltTextView androidbackground=drawablegradient_box androidlayout_height=wrap_content androidlayout_width=wrap_content gt

This application code gets the shape drawable and applies it to a View

Resources res = getResources() Drawable shape = res getDrawable(Rdrawablegradient_box)

TextView tv = (TextView)findViewByID(Ridtextview) tvsetBackground(shape)

Page 9: Android graphics mca 5th

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 9

void drawText(CharSequence text int start int end float x float

y Paint paint) Draw the specified range of text specified by startend with its origin at (xy) in the specified Paint

void drawText(char[] text int index int count float x float y Paint paint) Draw the text with origin at (xy) using the specified paint

void drawText(String text int start int end float x float y Paint paint) Draw the text with origin at (xy) using the specified paint

void drawTextOnPath(String text Path path float hOffset float vOffset Paint paint)

Draw the text with origin at (xy) using the specified paint along the specified path

void drawTextOnPath(char[] text int index int count Path path float hOffset float vOffset Paint paint)

Draw the text with origin at (xy) using the specified paint along the specified path

int getHeight() Returns the height of the current drawing layer

void getMatrix(Matrix ctm) Return in ctm the current transformation matrix

final Matrix

getMatrix() Return a new matrix with a copy of the canvas current transformation matrix

int getWidth() Returns the width of the current drawing layer

void rotate(float degrees) Preconcat the current matrix with the specified rotation

final void

rotate(float degrees float px float py) Preconcat the current matrix with the specified rotation

void scale(float sx float sy) Preconcat the current matrix with the specified scale

final

void scale(float sx float sy float px float py)

Preconcat the current matrix with the specified scale

void setBitmap(Bitmap bitmap)

Specify a bitmap for the canvas to draw into

void translate(float dx float dy)

Preconcat the current matrix with the specified translation

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 10

Paint class

The Paint class holds the style and color information about how to draw

geometries text and bitmaps

Paint Styles

public static final PaintStyle FILL

Geometry and text drawn with this style will be filled ignoring all stroke-related

settings in the paint

public static final PaintStyle FILL_AND_STROKE

Geometry and text drawn with this style will be both filled and stroked at the same time respecting the stroke-related fields on the paint This mode can give unexpected results if the geometry is oriented counter-clockwise This restriction

does not apply to either FILL or STROKE

public static final PaintStyle STROKE

Geometry and text drawn with this style will be stroked respecting the stroke-related fields on the paint

Public Constructors

Paint()

Create a new paint with default settings

Paint(int flags)

Create a new paint with the specified flags

Paint(Paint paint)

Create a new paint initialized with the attributes in the specified paint parameter

Public Methods

int getAlpha()

Helper to getColor() that just returns the colors alpha value

int getColor()

Return the paints color

ColorFilter getColorFilter()

Get the paints colorfilter (maybe be null)

boolean

getFillPath(Path src Path dst)

Applies anyall effects (patheffect stroking) to src returning

the result in dst

int getFlags()

Return the paints flags

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 11

PaintFontMetrics

getFontMetrics()

Allocates a new FontMetrics object and then calls

getFontMetrics(fm) with it returning the object

int

getFontMetricsInt(PaintFontMetricsInt fmi)

Return the fonts interline spacing given the Paints settings

for typeface textSize etc

float

getFontSpacing()

Return the recommend line spacing based on the current

typeface and text size

MaskFilter getMaskFilter()

Get the paints maskfilter object

Shader getShader()

Get the paints shader object

PaintStyle

getStyle()

Return the paints style used for controlling how primitives

geometries are interpreted (except for drawBitmap which

always assumes FILL_STYLE)

PaintAlign getTextAlign()

Return the paints Align value for drawing text

void

getTextBounds(char[] text int index int count Rect bounds)

Return in bounds (allocated by the caller) the smallest

rectangle that encloses all of the characters with an implied

origin at (00)

void

getTextBounds(String text int start int end Rect bounds)

Return in bounds (allocated by the caller) the smallest

rectangle that encloses all of the characters with an implied

origin at (00)

void

getTextPath(String text int start int end float x float y Path

path)

Return the path (outline) for the specified text

void

getTextPath(char[] text int index int count float x float y

Path path)

Return the path (outline) for the specified text

float getTextScaleX()

Return the paints horizontal scale factor for text

float getTextSize()

Return the paints text size

int getTextWidths(String text float[] widths)

Return the advance widths for the characters in the string

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 12

int

getTextWidths(CharSequence text int start int end float[]

widths)

Return the advance widths for the characters in the string

int getTextWidths(String text int start int end float[] widths)

Return the advance widths for the characters in the string

int getTextWidths(char[] text int index int count float[] widths)

Return the advance widths for the characters in the string

Typeface getTypeface()

Get the paints typeface object

final boolean

isAntiAlias()

Helper for getFlags() returning true if ANTI_ALIAS_FLAG bit is

set AntiAliasing smooths out the edges of what is being

drawn but is has no impact on the interior of the shape

final boolean

isStrikeThruText()

Helper for getFlags() returning true if

STRIKE_THRU_TEXT_FLAG bit is set

final boolean

isSubpixelText()

Helper for getFlags() returning true if SUBPIXEL_TEXT_FLAG

bit is set

final boolean

isUnderlineText()

Helper for getFlags() returning true if

UNDERLINE_TEXT_FLAG bit is set

float measureText(String text)

Return the width of the text

float measureText(CharSequence text int start int end)

Return the width of the text

float measureText(String text int start int end)

Return the width of the text

float measureText(char[] text int index int count)

Return the width of the text

void reset()

Restores the paint to its default settings

void set(Paint src)

Copy the fields from src into this paint

void

setARGB(int a int r int g int b)

Helper to setColor() that takes argb and constructs the

color int

void setAlpha(int a)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 13

Helper to setColor() that only assigns the colors alpha value

leaving its rgb values unchanged

void

setAntiAlias(boolean aa)

Helper for setFlags() setting or clearing the ANTI_ALIAS_FLAG

bit AntiAliasing smooths out the edges of what is being drawn

but is has no impact on the interior of the shape

void setColor(int color)

Set the paints color

ColorFilter setColorFilter(ColorFilter filter)

Set or clear the paints colorfilter returning the parameter

void

setFakeBoldText(boolean fakeBoldText)

Helper for setFlags() setting or clearing the

FAKE_BOLD_TEXT_FLAG bit

void setFlags(int flags)

Set the paints flags

PathEffect setPathEffect(PathEffect effect)

Set or clear the patheffect object

Shader setShader(Shader shader)

Set or clear the shader object

void

setShadowLayer(float radius float dx float dy int color)

This draws a shadow layer below the main layer with the

specified offset and color and blur radius

void

setStrikeThruText(boolean strikeThruText)

Helper for setFlags() setting or clearing the

STRIKE_THRU_TEXT_FLAG bit

void

setStyle(PaintStyle style)

Set the paints style used for controlling how primitives

geometries are interpreted (except for drawBitmap which

always assumes Fill)

void

setSubpixelText(boolean subpixelText)

Helper for setFlags() setting or clearing the

SUBPIXEL_TEXT_FLAG bit

void setTextAlign(PaintAlign align)

Set the paints text alignment

void setTextSize(float textSize)

Set the paints text size

void setTextSkewX(float skewX)

Set the paints horizontal skew factor for text

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 14

Typeface setTypeface(Typeface typeface)

Set or clear the typeface object

void

setUnderlineText(boolean underlineText)

Helper for setFlags() setting or clearing the

UNDERLINE_TEXT_FLAG bit

Types of Gradient

1 Linear Gradient

public LinearGradient (float x0 float y0 float x1 float y1 int[] colors float[]

positions ShaderTileMode tile)

Create a shader that draws a linear gradient along a line

Parameters

x0 The x-coordinate for the start of the gradient line

y0 The y-coordinate for the start of the gradient line

x1 The x-coordinate for the end of the gradient line

y1 The y-coordinate for the end of the gradient line

colors The colors to be distributed along the gradient line

positions

May be null The relative positions [01] of each corresponding color in

the colors array If this is null the the colors are distributed evenly

along the gradient line

tile The Shader tiling mode

2 Sweep Gradient

public SweepGradient (float cx float cy int[] colors float[] positions)

A subclass of Shader that draws a sweep gradient around a center point

Parameters

cx The x-coordinate of the center

cy The y-coordinate of the center

colors The colors to be distributed between around the center There must be

at least 2 colors in the array

positions

May be NULL The relative position of each corresponding color in the

colors array beginning with 0 and ending with 10 If the values are not

monotonic the drawing may produce unexpected results If positions is

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 15

NULL then the colors are automatically spaced evenly

3 Radial Gradient

public RadialGradient (float x float y float radius int[] colors float[] positions

ShaderTileMode tile)

Create a shader that draws a radial gradient given the center and radius

Parameters

x The x-coordinate of the center of the radius

y The y-coordinate of the center of the radius

radius Must be positive The radius of the circle for this gradient

colors The colors to be distributed between the center and edge of the circle

positions

May be NULL The relative position of each corresponding color in the

colors array If this is NULL the the colors are distributed evenly

between the center and edge of the circle

tile The Shader tiling mode

Shader Class

Shader is the based class for objects that return horizontal spans of colors during

drawing A subclass of Shader is installed in a Paint calling

paintsetShader(shader) After that any object (other than a bitmap) that is drawn

with that paint will get its color(s) from the shader

ShaderTileMode CLAMP replicate the edge color if the shader draws

outside of its original bounds

ShaderTileMode MIRROR repeat the shaders image horizontally and

vertically alternating mirror images so that adjacent images always seam

ShaderTileMode REPEAT repeat the shaders image horizontally and

vertically

Color

The Color class defines methods for creating and converting color ints Colors are

represented as packed ints made up of 4 bytes alpha red green blue The

values are unpremultiplied meaning any transparency is stored solely in the

alpha component and not in the color components The components are stored as

follows (alpha ltlt 24) | (red ltlt 16) | (green ltlt 8) | blue Each component ranges

between 0255 with 0 meaning no contribution for that component and 255

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 16

meaning 100 contribution Thus opaque-black would be 0xFF000000 (100

opaque but no contributions from red green or blue) and opaque-white would be

0xFFFFFFFF

Constant

int BLACK int LTGRAY

int BLUE int MAGENTA

int CYAN int RED

int DKGRAY int TRANSPARENT

int GRAY int WHITE

int GREEN int YELLOW

Public Constructors

Color()

Public Methods

static int HSVToColor(float[] hsv)

Convert HSV components to an ARGB color

static int HSVToColor(int alpha float[] hsv)

Convert HSV components to an ARGB color

static void RGBToHSV(int red int green int blue float[] hsv)

Convert RGB components to HSV

static int alpha(int color)

Return the alpha component of a color int

static int argb(int alpha int red int green int blue)

Return a color-int from alpha red green blue components

static int blue(int color)

Return the blue component of a color int

static void colorToHSV(int color float[] hsv)

Convert the argb color to its HSV components

static int green(int color)

Return the green component of a color int

static int parseColor(String colorString)

Parse the color string and return the corresponding color-int

static int red(int color)

Return the red component of a color int

static int rgb(int red int green int blue)

Return a color-int from red green blue components

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 17

Working with Text

Android provide several default fonts typeface and styles Application can also use

custom fonts by including font files as application assets and loading them using

the AssetManger same as recourses

Typeface class

The Typeface class specifies the typeface and intrinsic style of a font This is used

in the paint along with optionally Paint settings like textSize textSkewX

textScaleX to specify how text appears when drawn (and measured)

Constant

int BOLD

int BOLD_ITALIC

int ITALIC

int NORMAL

Fields

public static

final Typeface DEFAULT The default NORMAL typeface object

public static

final Typeface DEFAULT_BOLD The default BOLD typeface object

public static

final Typeface MONOSPACE The NORMAL style of the default monospace typeface

public static

final Typeface SANS_SERIF The NORMAL style of the default sans serif typeface

public static

final Typeface SERIF The NORMAL style of the default serif typeface

Public Methods

static

Typeface

create(String familyName int style)

Create a typeface object given a family name and option style

information

static

Typeface

create(Typeface family int style)

Create a typeface object that best matches the specified existing typeface

and the specified Style

static

Typeface

createFromAsset(AssetManager mgr String path)

Create a new typeface from the specified font data

static

Typeface

createFromFile(String path)

Create a new typeface from the specified font file

static createFromFile(File path)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 18

Typeface Create a new typeface from the specified font file

static

Typeface

defaultFromStyle(int style)

Returns one of the default typeface objects based on the specified style

int getStyle()

Returns the typefaces intrinsic style attributes

final

boolean

isBold()

Returns true if getStyle() has the BOLD bit set

final

boolean

isItalic()

Returns true if getStyle() has the ITALIC bit set

Using Default Fonts and Typefaces

By default Android uses the Sans Serif typeface but Monospace and Serif

typefaces are also available The following code excerpt draws some antialiased text in the default typeface (Sans Serif) to a Canvas

import androidgraphicsCanvas import androidgraphicsColor import androidgraphicsPaint import androidgraphicsTypeface Paint mPaint = new Paint(PaintANTI_ALIAS_FLAG) Typeface mType mPaintsetTextSize(16) mPaintsetTypeface(null) canvasdrawText(ldquoDefault Typefacerdquo 20 20 mPaint) You can instead load a different typeface such as Monotype

Typeface mType = Typefacecreate(TypefaceMONOSPACE TypefaceNORMAL) Perhaps you would prefer italic text in which case you can simply set the style of the typeface and the font family

Typeface mType = Typefacecreate(TypefaceSERIF TypefaceITALIC)

You can set certain properties of a typeface such as antialiasing underlining and strikethrough using the setFlags() method of the Paint object

mPaintsetFlags(PaintUNDERLINE_TEXT_FLAG)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 19

Loading Custom typeface from asset

Typeface mType = TypefacecreateFromAsset(getContext()getAssets()ldquofontschess1ttfrdquo) Example ViewFontjava

package compritesh

import androidcontentContext import androidgraphicsCanvas import androidgraphicsColor import androidgraphicsPaint import androidgraphicsTypeface import androidviewView public class ViewFont extends View Context c public ViewFont(Context context) super(context) c=context protected void onDraw(Canvas canvas) Typeface mType = TypefacecreateFromAsset( cgetAssets() fontsBaroqueScriptttf) Paint p =new Paint(PaintANTI_ALIAS_FLAG) psetTypeface(mType) psetTextSize(20) canvasdrawColor(ColorBLUE) canvasdrawText(Welcome to Android canvasgetWidth()4 canvasgetHeight()3 p)

SampleCustomFontjava package compritesh import androidappActivity import androidgraphicsTypeface import androidosBundle public class SampleCustomFont extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain) setContentView(new ViewFont(this))

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 20

Working with Bitmap and Matrix Bitmap

In computer graphics a bitmap or pixmap is a type of memory organization

or image file format used to store digital images The term bitmap comes from the

computer programming terminology meaning just a map of bits a spatially mapped array of bits Now along with pixmap it commonly refers to the similar

concept of a spatially mapped array of pixels Raster images in general may be referred to as bitmaps or pixmaps whether synthetic or photographic in files or

memory In certain contexts the term bitmap implies one bit per pixel while pixmap

is used for images with multiple bits per pixel

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 21

Shape Drawable in XML

This is a generic shape defined in XML

File location

resdrawablefilenamexml

The filename is used as the resource ID

Compiled resource datatype

Resource pointer to a GradientDrawable

Resource reference

In Java Rdrawablefilename

In XML [package]drawablefilename

Syntax

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=[rectangle | oval | line | ring] gt ltcorners androidradius=integer androidtopLeftRadius=integer androidtopRightRadius=integer androidbottomLeftRadius=integer androidbottomRightRadius=integer gt ltgradient androidangle=integer androidcenterX=integer androidcenterY=integer androidcenterColor=integer androidendColor=color androidgradientRadius=integer androidstartColor=color androidtype=[linear | radial | sweep] androidusesLevel=[true | false] gt ltpadding androidleft=integer androidtop=integer androidright=integer androidbottom=integer gt ltsize androidwidth=integer androidheight=integer gt ltsolid

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 22

androidcolor=color gt ltstroke androidwidth=integer androidcolor=color androiddashWidth=integer androiddashGap=integer gt ltshapegt

Elements

ltshapegt

The shape drawable This must be the root element

Attributes

xmlnsandroid

String Required Defines the XML namespace which must be

httpschemasandroidcomapkresandroid

androidshape

Keyword Defines the type of shape Valid values are

Value Desciption

rectangle A rectangle that fills the containing View This is the default shape

oval An oval shape that fits the dimensions of the containing View

line A horizontal line that spans the width of the containing View This

shape requires the ltstrokegt element to define the width of the line

ring A ring shape

The following attributes are used only when androidshape=ring

androidinnerRadius

Dimension The radius for the inner part of the ring (the hole in the middle)

as a dimension value or dimension resource

androidinnerRadiusRatio

Float The radius for the inner part of the ring expressed as a ratio of the

rings width For instance if androidinnerRadiusRatio=5 then the inner

radius equals the rings width divided by 5 This value is overridden by

androidinnerRadius Default value is 9

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 23

androidthickness

Dimension The thickness of the ring as a dimension value or dimension

resource

androidthicknessRatio

Float The thickness of the ring expressed as a ratio of the rings width For

instance if androidthicknessRatio=2 then the thickness equals the rings

width divided by 2 This value is overridden by androidinnerRadius Default

value is 3

androiduseLevel

Boolean true if this is used as a LevelListDrawable This should normally

be false or your shape may not appear

ltcornersgt

Creates rounded corners for the shape Applies only when the shape is a

rectangle

Attributes

androidradius

Dimension The radius for all corners as a dimension value or dimension

resource This is overridden for each corner by the following attributes

androidtopLeftRadius

Dimension The radius for the top-left corner as a dimension value or

dimension resource

androidtopRightRadius

Dimension The radius for the top-right corner as a dimension value or

dimension resource

androidbottomLeftRadius

Dimension The radius for the bottom-left corner as a dimension value or

dimension resource

androidbottomRightRadius

Dimension The radius for the bottom-right corner as a dimension value or

dimension resource

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 24

Note Every corner must (initially) be provided a corner radius greater than

1 or else no corners are rounded If you want specific corners to not be rounded a work-around is to use androidradius to set a default corner

radius greater than 1 but then override each and every corner with the values you really want providing zero (0dp) where you dont want rounded

corners

ltgradientgt

Specifies a gradient color for the shape

Attributes

androidangle

Integer The angle for the gradient in degrees 0 is left to right 90 is bottom

to top It must be a multiple of 45 Default is 0

androidcenterX

Float The relative X-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterY

Float The relative Y-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterColor

Color Optional color that comes between the start and end colors as a

hexadecimal value or color resource

androidendColor

Color The ending color as a hexadecimal value or color resource

androidgradientRadius

Float The radius for the gradient Only applied when androidtype=radial

androidstartColor

Color The starting color as a hexadecimal value or color resource

androidtype

Keyword The type of gradient pattern to apply Valid values are

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 25

Value Description

linear A linear gradient This is the default

radial A radial gradient The start color is the center color

sweep A sweeping line gradient

androiduseLevel

Boolean true if this is used as a LevelListDrawable

ltpaddinggt

Padding to apply to the containing View element (this pads the position of

the View content not the shape)

Attributes

androidleft

Dimension Left padding as a dimension value or dimension resource

androidtop

Dimension Top padding as a dimension value or dimension resource

androidright

Dimension Right padding as a dimension value or dimension resource

androidbottom

Dimension Bottom padding as a dimension value or dimension resource

ltsizegt

The size of the shape

Attributes

androidheight

Dimension The height of the shape as a dimension value or dimension

resource

androidwidth

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 26

Dimension The width of the shape as a dimension value or dimension

resource

Note The shape scales to the size of the container View proportionate to the

dimensions defined here by default When you use the shape in an ImageView you can restrict scaling by setting the androidscaleType to center

ltsolidgt

A solid color to fill the shape

Attributes

androidcolor

Color The color to apply to the shape as a hexadecimal value or color

resource

ltstrokegt

A stroke line for the shape

Attributes

androidwidth

Dimension The thickness of the line as a dimension value or dimension

resource

androidcolor

Color The color of the line as a hexadecimal value or color resource

androiddashGap

Dimension The distance between line dashes as a dimension value or

dimension resource Only valid if androiddashWidth is set

androiddashWidth

Dimension The size of each dash line as a dimension value or dimension

resource Only valid if androiddashGap is set

Example

XML file saved at resdrawablegradient_boxxml

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 27

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=rectanglegt ltgradient androidstartColor=FFFF0000 androidendColor=80FF00FF androidangle=45gt ltpadding androidleft=7dp androidtop=7dp androidright=7dp androidbottom=7dp gt ltcorners androidradius=8dp gt ltshapegt

This layout XML applies the shape drawable to a View

ltTextView androidbackground=drawablegradient_box androidlayout_height=wrap_content androidlayout_width=wrap_content gt

This application code gets the shape drawable and applies it to a View

Resources res = getResources() Drawable shape = res getDrawable(Rdrawablegradient_box)

TextView tv = (TextView)findViewByID(Ridtextview) tvsetBackground(shape)

Page 10: Android graphics mca 5th

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 10

Paint class

The Paint class holds the style and color information about how to draw

geometries text and bitmaps

Paint Styles

public static final PaintStyle FILL

Geometry and text drawn with this style will be filled ignoring all stroke-related

settings in the paint

public static final PaintStyle FILL_AND_STROKE

Geometry and text drawn with this style will be both filled and stroked at the same time respecting the stroke-related fields on the paint This mode can give unexpected results if the geometry is oriented counter-clockwise This restriction

does not apply to either FILL or STROKE

public static final PaintStyle STROKE

Geometry and text drawn with this style will be stroked respecting the stroke-related fields on the paint

Public Constructors

Paint()

Create a new paint with default settings

Paint(int flags)

Create a new paint with the specified flags

Paint(Paint paint)

Create a new paint initialized with the attributes in the specified paint parameter

Public Methods

int getAlpha()

Helper to getColor() that just returns the colors alpha value

int getColor()

Return the paints color

ColorFilter getColorFilter()

Get the paints colorfilter (maybe be null)

boolean

getFillPath(Path src Path dst)

Applies anyall effects (patheffect stroking) to src returning

the result in dst

int getFlags()

Return the paints flags

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 11

PaintFontMetrics

getFontMetrics()

Allocates a new FontMetrics object and then calls

getFontMetrics(fm) with it returning the object

int

getFontMetricsInt(PaintFontMetricsInt fmi)

Return the fonts interline spacing given the Paints settings

for typeface textSize etc

float

getFontSpacing()

Return the recommend line spacing based on the current

typeface and text size

MaskFilter getMaskFilter()

Get the paints maskfilter object

Shader getShader()

Get the paints shader object

PaintStyle

getStyle()

Return the paints style used for controlling how primitives

geometries are interpreted (except for drawBitmap which

always assumes FILL_STYLE)

PaintAlign getTextAlign()

Return the paints Align value for drawing text

void

getTextBounds(char[] text int index int count Rect bounds)

Return in bounds (allocated by the caller) the smallest

rectangle that encloses all of the characters with an implied

origin at (00)

void

getTextBounds(String text int start int end Rect bounds)

Return in bounds (allocated by the caller) the smallest

rectangle that encloses all of the characters with an implied

origin at (00)

void

getTextPath(String text int start int end float x float y Path

path)

Return the path (outline) for the specified text

void

getTextPath(char[] text int index int count float x float y

Path path)

Return the path (outline) for the specified text

float getTextScaleX()

Return the paints horizontal scale factor for text

float getTextSize()

Return the paints text size

int getTextWidths(String text float[] widths)

Return the advance widths for the characters in the string

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 12

int

getTextWidths(CharSequence text int start int end float[]

widths)

Return the advance widths for the characters in the string

int getTextWidths(String text int start int end float[] widths)

Return the advance widths for the characters in the string

int getTextWidths(char[] text int index int count float[] widths)

Return the advance widths for the characters in the string

Typeface getTypeface()

Get the paints typeface object

final boolean

isAntiAlias()

Helper for getFlags() returning true if ANTI_ALIAS_FLAG bit is

set AntiAliasing smooths out the edges of what is being

drawn but is has no impact on the interior of the shape

final boolean

isStrikeThruText()

Helper for getFlags() returning true if

STRIKE_THRU_TEXT_FLAG bit is set

final boolean

isSubpixelText()

Helper for getFlags() returning true if SUBPIXEL_TEXT_FLAG

bit is set

final boolean

isUnderlineText()

Helper for getFlags() returning true if

UNDERLINE_TEXT_FLAG bit is set

float measureText(String text)

Return the width of the text

float measureText(CharSequence text int start int end)

Return the width of the text

float measureText(String text int start int end)

Return the width of the text

float measureText(char[] text int index int count)

Return the width of the text

void reset()

Restores the paint to its default settings

void set(Paint src)

Copy the fields from src into this paint

void

setARGB(int a int r int g int b)

Helper to setColor() that takes argb and constructs the

color int

void setAlpha(int a)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 13

Helper to setColor() that only assigns the colors alpha value

leaving its rgb values unchanged

void

setAntiAlias(boolean aa)

Helper for setFlags() setting or clearing the ANTI_ALIAS_FLAG

bit AntiAliasing smooths out the edges of what is being drawn

but is has no impact on the interior of the shape

void setColor(int color)

Set the paints color

ColorFilter setColorFilter(ColorFilter filter)

Set or clear the paints colorfilter returning the parameter

void

setFakeBoldText(boolean fakeBoldText)

Helper for setFlags() setting or clearing the

FAKE_BOLD_TEXT_FLAG bit

void setFlags(int flags)

Set the paints flags

PathEffect setPathEffect(PathEffect effect)

Set or clear the patheffect object

Shader setShader(Shader shader)

Set or clear the shader object

void

setShadowLayer(float radius float dx float dy int color)

This draws a shadow layer below the main layer with the

specified offset and color and blur radius

void

setStrikeThruText(boolean strikeThruText)

Helper for setFlags() setting or clearing the

STRIKE_THRU_TEXT_FLAG bit

void

setStyle(PaintStyle style)

Set the paints style used for controlling how primitives

geometries are interpreted (except for drawBitmap which

always assumes Fill)

void

setSubpixelText(boolean subpixelText)

Helper for setFlags() setting or clearing the

SUBPIXEL_TEXT_FLAG bit

void setTextAlign(PaintAlign align)

Set the paints text alignment

void setTextSize(float textSize)

Set the paints text size

void setTextSkewX(float skewX)

Set the paints horizontal skew factor for text

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 14

Typeface setTypeface(Typeface typeface)

Set or clear the typeface object

void

setUnderlineText(boolean underlineText)

Helper for setFlags() setting or clearing the

UNDERLINE_TEXT_FLAG bit

Types of Gradient

1 Linear Gradient

public LinearGradient (float x0 float y0 float x1 float y1 int[] colors float[]

positions ShaderTileMode tile)

Create a shader that draws a linear gradient along a line

Parameters

x0 The x-coordinate for the start of the gradient line

y0 The y-coordinate for the start of the gradient line

x1 The x-coordinate for the end of the gradient line

y1 The y-coordinate for the end of the gradient line

colors The colors to be distributed along the gradient line

positions

May be null The relative positions [01] of each corresponding color in

the colors array If this is null the the colors are distributed evenly

along the gradient line

tile The Shader tiling mode

2 Sweep Gradient

public SweepGradient (float cx float cy int[] colors float[] positions)

A subclass of Shader that draws a sweep gradient around a center point

Parameters

cx The x-coordinate of the center

cy The y-coordinate of the center

colors The colors to be distributed between around the center There must be

at least 2 colors in the array

positions

May be NULL The relative position of each corresponding color in the

colors array beginning with 0 and ending with 10 If the values are not

monotonic the drawing may produce unexpected results If positions is

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 15

NULL then the colors are automatically spaced evenly

3 Radial Gradient

public RadialGradient (float x float y float radius int[] colors float[] positions

ShaderTileMode tile)

Create a shader that draws a radial gradient given the center and radius

Parameters

x The x-coordinate of the center of the radius

y The y-coordinate of the center of the radius

radius Must be positive The radius of the circle for this gradient

colors The colors to be distributed between the center and edge of the circle

positions

May be NULL The relative position of each corresponding color in the

colors array If this is NULL the the colors are distributed evenly

between the center and edge of the circle

tile The Shader tiling mode

Shader Class

Shader is the based class for objects that return horizontal spans of colors during

drawing A subclass of Shader is installed in a Paint calling

paintsetShader(shader) After that any object (other than a bitmap) that is drawn

with that paint will get its color(s) from the shader

ShaderTileMode CLAMP replicate the edge color if the shader draws

outside of its original bounds

ShaderTileMode MIRROR repeat the shaders image horizontally and

vertically alternating mirror images so that adjacent images always seam

ShaderTileMode REPEAT repeat the shaders image horizontally and

vertically

Color

The Color class defines methods for creating and converting color ints Colors are

represented as packed ints made up of 4 bytes alpha red green blue The

values are unpremultiplied meaning any transparency is stored solely in the

alpha component and not in the color components The components are stored as

follows (alpha ltlt 24) | (red ltlt 16) | (green ltlt 8) | blue Each component ranges

between 0255 with 0 meaning no contribution for that component and 255

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 16

meaning 100 contribution Thus opaque-black would be 0xFF000000 (100

opaque but no contributions from red green or blue) and opaque-white would be

0xFFFFFFFF

Constant

int BLACK int LTGRAY

int BLUE int MAGENTA

int CYAN int RED

int DKGRAY int TRANSPARENT

int GRAY int WHITE

int GREEN int YELLOW

Public Constructors

Color()

Public Methods

static int HSVToColor(float[] hsv)

Convert HSV components to an ARGB color

static int HSVToColor(int alpha float[] hsv)

Convert HSV components to an ARGB color

static void RGBToHSV(int red int green int blue float[] hsv)

Convert RGB components to HSV

static int alpha(int color)

Return the alpha component of a color int

static int argb(int alpha int red int green int blue)

Return a color-int from alpha red green blue components

static int blue(int color)

Return the blue component of a color int

static void colorToHSV(int color float[] hsv)

Convert the argb color to its HSV components

static int green(int color)

Return the green component of a color int

static int parseColor(String colorString)

Parse the color string and return the corresponding color-int

static int red(int color)

Return the red component of a color int

static int rgb(int red int green int blue)

Return a color-int from red green blue components

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 17

Working with Text

Android provide several default fonts typeface and styles Application can also use

custom fonts by including font files as application assets and loading them using

the AssetManger same as recourses

Typeface class

The Typeface class specifies the typeface and intrinsic style of a font This is used

in the paint along with optionally Paint settings like textSize textSkewX

textScaleX to specify how text appears when drawn (and measured)

Constant

int BOLD

int BOLD_ITALIC

int ITALIC

int NORMAL

Fields

public static

final Typeface DEFAULT The default NORMAL typeface object

public static

final Typeface DEFAULT_BOLD The default BOLD typeface object

public static

final Typeface MONOSPACE The NORMAL style of the default monospace typeface

public static

final Typeface SANS_SERIF The NORMAL style of the default sans serif typeface

public static

final Typeface SERIF The NORMAL style of the default serif typeface

Public Methods

static

Typeface

create(String familyName int style)

Create a typeface object given a family name and option style

information

static

Typeface

create(Typeface family int style)

Create a typeface object that best matches the specified existing typeface

and the specified Style

static

Typeface

createFromAsset(AssetManager mgr String path)

Create a new typeface from the specified font data

static

Typeface

createFromFile(String path)

Create a new typeface from the specified font file

static createFromFile(File path)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 18

Typeface Create a new typeface from the specified font file

static

Typeface

defaultFromStyle(int style)

Returns one of the default typeface objects based on the specified style

int getStyle()

Returns the typefaces intrinsic style attributes

final

boolean

isBold()

Returns true if getStyle() has the BOLD bit set

final

boolean

isItalic()

Returns true if getStyle() has the ITALIC bit set

Using Default Fonts and Typefaces

By default Android uses the Sans Serif typeface but Monospace and Serif

typefaces are also available The following code excerpt draws some antialiased text in the default typeface (Sans Serif) to a Canvas

import androidgraphicsCanvas import androidgraphicsColor import androidgraphicsPaint import androidgraphicsTypeface Paint mPaint = new Paint(PaintANTI_ALIAS_FLAG) Typeface mType mPaintsetTextSize(16) mPaintsetTypeface(null) canvasdrawText(ldquoDefault Typefacerdquo 20 20 mPaint) You can instead load a different typeface such as Monotype

Typeface mType = Typefacecreate(TypefaceMONOSPACE TypefaceNORMAL) Perhaps you would prefer italic text in which case you can simply set the style of the typeface and the font family

Typeface mType = Typefacecreate(TypefaceSERIF TypefaceITALIC)

You can set certain properties of a typeface such as antialiasing underlining and strikethrough using the setFlags() method of the Paint object

mPaintsetFlags(PaintUNDERLINE_TEXT_FLAG)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 19

Loading Custom typeface from asset

Typeface mType = TypefacecreateFromAsset(getContext()getAssets()ldquofontschess1ttfrdquo) Example ViewFontjava

package compritesh

import androidcontentContext import androidgraphicsCanvas import androidgraphicsColor import androidgraphicsPaint import androidgraphicsTypeface import androidviewView public class ViewFont extends View Context c public ViewFont(Context context) super(context) c=context protected void onDraw(Canvas canvas) Typeface mType = TypefacecreateFromAsset( cgetAssets() fontsBaroqueScriptttf) Paint p =new Paint(PaintANTI_ALIAS_FLAG) psetTypeface(mType) psetTextSize(20) canvasdrawColor(ColorBLUE) canvasdrawText(Welcome to Android canvasgetWidth()4 canvasgetHeight()3 p)

SampleCustomFontjava package compritesh import androidappActivity import androidgraphicsTypeface import androidosBundle public class SampleCustomFont extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain) setContentView(new ViewFont(this))

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 20

Working with Bitmap and Matrix Bitmap

In computer graphics a bitmap or pixmap is a type of memory organization

or image file format used to store digital images The term bitmap comes from the

computer programming terminology meaning just a map of bits a spatially mapped array of bits Now along with pixmap it commonly refers to the similar

concept of a spatially mapped array of pixels Raster images in general may be referred to as bitmaps or pixmaps whether synthetic or photographic in files or

memory In certain contexts the term bitmap implies one bit per pixel while pixmap

is used for images with multiple bits per pixel

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 21

Shape Drawable in XML

This is a generic shape defined in XML

File location

resdrawablefilenamexml

The filename is used as the resource ID

Compiled resource datatype

Resource pointer to a GradientDrawable

Resource reference

In Java Rdrawablefilename

In XML [package]drawablefilename

Syntax

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=[rectangle | oval | line | ring] gt ltcorners androidradius=integer androidtopLeftRadius=integer androidtopRightRadius=integer androidbottomLeftRadius=integer androidbottomRightRadius=integer gt ltgradient androidangle=integer androidcenterX=integer androidcenterY=integer androidcenterColor=integer androidendColor=color androidgradientRadius=integer androidstartColor=color androidtype=[linear | radial | sweep] androidusesLevel=[true | false] gt ltpadding androidleft=integer androidtop=integer androidright=integer androidbottom=integer gt ltsize androidwidth=integer androidheight=integer gt ltsolid

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 22

androidcolor=color gt ltstroke androidwidth=integer androidcolor=color androiddashWidth=integer androiddashGap=integer gt ltshapegt

Elements

ltshapegt

The shape drawable This must be the root element

Attributes

xmlnsandroid

String Required Defines the XML namespace which must be

httpschemasandroidcomapkresandroid

androidshape

Keyword Defines the type of shape Valid values are

Value Desciption

rectangle A rectangle that fills the containing View This is the default shape

oval An oval shape that fits the dimensions of the containing View

line A horizontal line that spans the width of the containing View This

shape requires the ltstrokegt element to define the width of the line

ring A ring shape

The following attributes are used only when androidshape=ring

androidinnerRadius

Dimension The radius for the inner part of the ring (the hole in the middle)

as a dimension value or dimension resource

androidinnerRadiusRatio

Float The radius for the inner part of the ring expressed as a ratio of the

rings width For instance if androidinnerRadiusRatio=5 then the inner

radius equals the rings width divided by 5 This value is overridden by

androidinnerRadius Default value is 9

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 23

androidthickness

Dimension The thickness of the ring as a dimension value or dimension

resource

androidthicknessRatio

Float The thickness of the ring expressed as a ratio of the rings width For

instance if androidthicknessRatio=2 then the thickness equals the rings

width divided by 2 This value is overridden by androidinnerRadius Default

value is 3

androiduseLevel

Boolean true if this is used as a LevelListDrawable This should normally

be false or your shape may not appear

ltcornersgt

Creates rounded corners for the shape Applies only when the shape is a

rectangle

Attributes

androidradius

Dimension The radius for all corners as a dimension value or dimension

resource This is overridden for each corner by the following attributes

androidtopLeftRadius

Dimension The radius for the top-left corner as a dimension value or

dimension resource

androidtopRightRadius

Dimension The radius for the top-right corner as a dimension value or

dimension resource

androidbottomLeftRadius

Dimension The radius for the bottom-left corner as a dimension value or

dimension resource

androidbottomRightRadius

Dimension The radius for the bottom-right corner as a dimension value or

dimension resource

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 24

Note Every corner must (initially) be provided a corner radius greater than

1 or else no corners are rounded If you want specific corners to not be rounded a work-around is to use androidradius to set a default corner

radius greater than 1 but then override each and every corner with the values you really want providing zero (0dp) where you dont want rounded

corners

ltgradientgt

Specifies a gradient color for the shape

Attributes

androidangle

Integer The angle for the gradient in degrees 0 is left to right 90 is bottom

to top It must be a multiple of 45 Default is 0

androidcenterX

Float The relative X-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterY

Float The relative Y-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterColor

Color Optional color that comes between the start and end colors as a

hexadecimal value or color resource

androidendColor

Color The ending color as a hexadecimal value or color resource

androidgradientRadius

Float The radius for the gradient Only applied when androidtype=radial

androidstartColor

Color The starting color as a hexadecimal value or color resource

androidtype

Keyword The type of gradient pattern to apply Valid values are

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 25

Value Description

linear A linear gradient This is the default

radial A radial gradient The start color is the center color

sweep A sweeping line gradient

androiduseLevel

Boolean true if this is used as a LevelListDrawable

ltpaddinggt

Padding to apply to the containing View element (this pads the position of

the View content not the shape)

Attributes

androidleft

Dimension Left padding as a dimension value or dimension resource

androidtop

Dimension Top padding as a dimension value or dimension resource

androidright

Dimension Right padding as a dimension value or dimension resource

androidbottom

Dimension Bottom padding as a dimension value or dimension resource

ltsizegt

The size of the shape

Attributes

androidheight

Dimension The height of the shape as a dimension value or dimension

resource

androidwidth

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 26

Dimension The width of the shape as a dimension value or dimension

resource

Note The shape scales to the size of the container View proportionate to the

dimensions defined here by default When you use the shape in an ImageView you can restrict scaling by setting the androidscaleType to center

ltsolidgt

A solid color to fill the shape

Attributes

androidcolor

Color The color to apply to the shape as a hexadecimal value or color

resource

ltstrokegt

A stroke line for the shape

Attributes

androidwidth

Dimension The thickness of the line as a dimension value or dimension

resource

androidcolor

Color The color of the line as a hexadecimal value or color resource

androiddashGap

Dimension The distance between line dashes as a dimension value or

dimension resource Only valid if androiddashWidth is set

androiddashWidth

Dimension The size of each dash line as a dimension value or dimension

resource Only valid if androiddashGap is set

Example

XML file saved at resdrawablegradient_boxxml

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 27

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=rectanglegt ltgradient androidstartColor=FFFF0000 androidendColor=80FF00FF androidangle=45gt ltpadding androidleft=7dp androidtop=7dp androidright=7dp androidbottom=7dp gt ltcorners androidradius=8dp gt ltshapegt

This layout XML applies the shape drawable to a View

ltTextView androidbackground=drawablegradient_box androidlayout_height=wrap_content androidlayout_width=wrap_content gt

This application code gets the shape drawable and applies it to a View

Resources res = getResources() Drawable shape = res getDrawable(Rdrawablegradient_box)

TextView tv = (TextView)findViewByID(Ridtextview) tvsetBackground(shape)

Page 11: Android graphics mca 5th

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 11

PaintFontMetrics

getFontMetrics()

Allocates a new FontMetrics object and then calls

getFontMetrics(fm) with it returning the object

int

getFontMetricsInt(PaintFontMetricsInt fmi)

Return the fonts interline spacing given the Paints settings

for typeface textSize etc

float

getFontSpacing()

Return the recommend line spacing based on the current

typeface and text size

MaskFilter getMaskFilter()

Get the paints maskfilter object

Shader getShader()

Get the paints shader object

PaintStyle

getStyle()

Return the paints style used for controlling how primitives

geometries are interpreted (except for drawBitmap which

always assumes FILL_STYLE)

PaintAlign getTextAlign()

Return the paints Align value for drawing text

void

getTextBounds(char[] text int index int count Rect bounds)

Return in bounds (allocated by the caller) the smallest

rectangle that encloses all of the characters with an implied

origin at (00)

void

getTextBounds(String text int start int end Rect bounds)

Return in bounds (allocated by the caller) the smallest

rectangle that encloses all of the characters with an implied

origin at (00)

void

getTextPath(String text int start int end float x float y Path

path)

Return the path (outline) for the specified text

void

getTextPath(char[] text int index int count float x float y

Path path)

Return the path (outline) for the specified text

float getTextScaleX()

Return the paints horizontal scale factor for text

float getTextSize()

Return the paints text size

int getTextWidths(String text float[] widths)

Return the advance widths for the characters in the string

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 12

int

getTextWidths(CharSequence text int start int end float[]

widths)

Return the advance widths for the characters in the string

int getTextWidths(String text int start int end float[] widths)

Return the advance widths for the characters in the string

int getTextWidths(char[] text int index int count float[] widths)

Return the advance widths for the characters in the string

Typeface getTypeface()

Get the paints typeface object

final boolean

isAntiAlias()

Helper for getFlags() returning true if ANTI_ALIAS_FLAG bit is

set AntiAliasing smooths out the edges of what is being

drawn but is has no impact on the interior of the shape

final boolean

isStrikeThruText()

Helper for getFlags() returning true if

STRIKE_THRU_TEXT_FLAG bit is set

final boolean

isSubpixelText()

Helper for getFlags() returning true if SUBPIXEL_TEXT_FLAG

bit is set

final boolean

isUnderlineText()

Helper for getFlags() returning true if

UNDERLINE_TEXT_FLAG bit is set

float measureText(String text)

Return the width of the text

float measureText(CharSequence text int start int end)

Return the width of the text

float measureText(String text int start int end)

Return the width of the text

float measureText(char[] text int index int count)

Return the width of the text

void reset()

Restores the paint to its default settings

void set(Paint src)

Copy the fields from src into this paint

void

setARGB(int a int r int g int b)

Helper to setColor() that takes argb and constructs the

color int

void setAlpha(int a)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 13

Helper to setColor() that only assigns the colors alpha value

leaving its rgb values unchanged

void

setAntiAlias(boolean aa)

Helper for setFlags() setting or clearing the ANTI_ALIAS_FLAG

bit AntiAliasing smooths out the edges of what is being drawn

but is has no impact on the interior of the shape

void setColor(int color)

Set the paints color

ColorFilter setColorFilter(ColorFilter filter)

Set or clear the paints colorfilter returning the parameter

void

setFakeBoldText(boolean fakeBoldText)

Helper for setFlags() setting or clearing the

FAKE_BOLD_TEXT_FLAG bit

void setFlags(int flags)

Set the paints flags

PathEffect setPathEffect(PathEffect effect)

Set or clear the patheffect object

Shader setShader(Shader shader)

Set or clear the shader object

void

setShadowLayer(float radius float dx float dy int color)

This draws a shadow layer below the main layer with the

specified offset and color and blur radius

void

setStrikeThruText(boolean strikeThruText)

Helper for setFlags() setting or clearing the

STRIKE_THRU_TEXT_FLAG bit

void

setStyle(PaintStyle style)

Set the paints style used for controlling how primitives

geometries are interpreted (except for drawBitmap which

always assumes Fill)

void

setSubpixelText(boolean subpixelText)

Helper for setFlags() setting or clearing the

SUBPIXEL_TEXT_FLAG bit

void setTextAlign(PaintAlign align)

Set the paints text alignment

void setTextSize(float textSize)

Set the paints text size

void setTextSkewX(float skewX)

Set the paints horizontal skew factor for text

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 14

Typeface setTypeface(Typeface typeface)

Set or clear the typeface object

void

setUnderlineText(boolean underlineText)

Helper for setFlags() setting or clearing the

UNDERLINE_TEXT_FLAG bit

Types of Gradient

1 Linear Gradient

public LinearGradient (float x0 float y0 float x1 float y1 int[] colors float[]

positions ShaderTileMode tile)

Create a shader that draws a linear gradient along a line

Parameters

x0 The x-coordinate for the start of the gradient line

y0 The y-coordinate for the start of the gradient line

x1 The x-coordinate for the end of the gradient line

y1 The y-coordinate for the end of the gradient line

colors The colors to be distributed along the gradient line

positions

May be null The relative positions [01] of each corresponding color in

the colors array If this is null the the colors are distributed evenly

along the gradient line

tile The Shader tiling mode

2 Sweep Gradient

public SweepGradient (float cx float cy int[] colors float[] positions)

A subclass of Shader that draws a sweep gradient around a center point

Parameters

cx The x-coordinate of the center

cy The y-coordinate of the center

colors The colors to be distributed between around the center There must be

at least 2 colors in the array

positions

May be NULL The relative position of each corresponding color in the

colors array beginning with 0 and ending with 10 If the values are not

monotonic the drawing may produce unexpected results If positions is

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 15

NULL then the colors are automatically spaced evenly

3 Radial Gradient

public RadialGradient (float x float y float radius int[] colors float[] positions

ShaderTileMode tile)

Create a shader that draws a radial gradient given the center and radius

Parameters

x The x-coordinate of the center of the radius

y The y-coordinate of the center of the radius

radius Must be positive The radius of the circle for this gradient

colors The colors to be distributed between the center and edge of the circle

positions

May be NULL The relative position of each corresponding color in the

colors array If this is NULL the the colors are distributed evenly

between the center and edge of the circle

tile The Shader tiling mode

Shader Class

Shader is the based class for objects that return horizontal spans of colors during

drawing A subclass of Shader is installed in a Paint calling

paintsetShader(shader) After that any object (other than a bitmap) that is drawn

with that paint will get its color(s) from the shader

ShaderTileMode CLAMP replicate the edge color if the shader draws

outside of its original bounds

ShaderTileMode MIRROR repeat the shaders image horizontally and

vertically alternating mirror images so that adjacent images always seam

ShaderTileMode REPEAT repeat the shaders image horizontally and

vertically

Color

The Color class defines methods for creating and converting color ints Colors are

represented as packed ints made up of 4 bytes alpha red green blue The

values are unpremultiplied meaning any transparency is stored solely in the

alpha component and not in the color components The components are stored as

follows (alpha ltlt 24) | (red ltlt 16) | (green ltlt 8) | blue Each component ranges

between 0255 with 0 meaning no contribution for that component and 255

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 16

meaning 100 contribution Thus opaque-black would be 0xFF000000 (100

opaque but no contributions from red green or blue) and opaque-white would be

0xFFFFFFFF

Constant

int BLACK int LTGRAY

int BLUE int MAGENTA

int CYAN int RED

int DKGRAY int TRANSPARENT

int GRAY int WHITE

int GREEN int YELLOW

Public Constructors

Color()

Public Methods

static int HSVToColor(float[] hsv)

Convert HSV components to an ARGB color

static int HSVToColor(int alpha float[] hsv)

Convert HSV components to an ARGB color

static void RGBToHSV(int red int green int blue float[] hsv)

Convert RGB components to HSV

static int alpha(int color)

Return the alpha component of a color int

static int argb(int alpha int red int green int blue)

Return a color-int from alpha red green blue components

static int blue(int color)

Return the blue component of a color int

static void colorToHSV(int color float[] hsv)

Convert the argb color to its HSV components

static int green(int color)

Return the green component of a color int

static int parseColor(String colorString)

Parse the color string and return the corresponding color-int

static int red(int color)

Return the red component of a color int

static int rgb(int red int green int blue)

Return a color-int from red green blue components

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 17

Working with Text

Android provide several default fonts typeface and styles Application can also use

custom fonts by including font files as application assets and loading them using

the AssetManger same as recourses

Typeface class

The Typeface class specifies the typeface and intrinsic style of a font This is used

in the paint along with optionally Paint settings like textSize textSkewX

textScaleX to specify how text appears when drawn (and measured)

Constant

int BOLD

int BOLD_ITALIC

int ITALIC

int NORMAL

Fields

public static

final Typeface DEFAULT The default NORMAL typeface object

public static

final Typeface DEFAULT_BOLD The default BOLD typeface object

public static

final Typeface MONOSPACE The NORMAL style of the default monospace typeface

public static

final Typeface SANS_SERIF The NORMAL style of the default sans serif typeface

public static

final Typeface SERIF The NORMAL style of the default serif typeface

Public Methods

static

Typeface

create(String familyName int style)

Create a typeface object given a family name and option style

information

static

Typeface

create(Typeface family int style)

Create a typeface object that best matches the specified existing typeface

and the specified Style

static

Typeface

createFromAsset(AssetManager mgr String path)

Create a new typeface from the specified font data

static

Typeface

createFromFile(String path)

Create a new typeface from the specified font file

static createFromFile(File path)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 18

Typeface Create a new typeface from the specified font file

static

Typeface

defaultFromStyle(int style)

Returns one of the default typeface objects based on the specified style

int getStyle()

Returns the typefaces intrinsic style attributes

final

boolean

isBold()

Returns true if getStyle() has the BOLD bit set

final

boolean

isItalic()

Returns true if getStyle() has the ITALIC bit set

Using Default Fonts and Typefaces

By default Android uses the Sans Serif typeface but Monospace and Serif

typefaces are also available The following code excerpt draws some antialiased text in the default typeface (Sans Serif) to a Canvas

import androidgraphicsCanvas import androidgraphicsColor import androidgraphicsPaint import androidgraphicsTypeface Paint mPaint = new Paint(PaintANTI_ALIAS_FLAG) Typeface mType mPaintsetTextSize(16) mPaintsetTypeface(null) canvasdrawText(ldquoDefault Typefacerdquo 20 20 mPaint) You can instead load a different typeface such as Monotype

Typeface mType = Typefacecreate(TypefaceMONOSPACE TypefaceNORMAL) Perhaps you would prefer italic text in which case you can simply set the style of the typeface and the font family

Typeface mType = Typefacecreate(TypefaceSERIF TypefaceITALIC)

You can set certain properties of a typeface such as antialiasing underlining and strikethrough using the setFlags() method of the Paint object

mPaintsetFlags(PaintUNDERLINE_TEXT_FLAG)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 19

Loading Custom typeface from asset

Typeface mType = TypefacecreateFromAsset(getContext()getAssets()ldquofontschess1ttfrdquo) Example ViewFontjava

package compritesh

import androidcontentContext import androidgraphicsCanvas import androidgraphicsColor import androidgraphicsPaint import androidgraphicsTypeface import androidviewView public class ViewFont extends View Context c public ViewFont(Context context) super(context) c=context protected void onDraw(Canvas canvas) Typeface mType = TypefacecreateFromAsset( cgetAssets() fontsBaroqueScriptttf) Paint p =new Paint(PaintANTI_ALIAS_FLAG) psetTypeface(mType) psetTextSize(20) canvasdrawColor(ColorBLUE) canvasdrawText(Welcome to Android canvasgetWidth()4 canvasgetHeight()3 p)

SampleCustomFontjava package compritesh import androidappActivity import androidgraphicsTypeface import androidosBundle public class SampleCustomFont extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain) setContentView(new ViewFont(this))

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 20

Working with Bitmap and Matrix Bitmap

In computer graphics a bitmap or pixmap is a type of memory organization

or image file format used to store digital images The term bitmap comes from the

computer programming terminology meaning just a map of bits a spatially mapped array of bits Now along with pixmap it commonly refers to the similar

concept of a spatially mapped array of pixels Raster images in general may be referred to as bitmaps or pixmaps whether synthetic or photographic in files or

memory In certain contexts the term bitmap implies one bit per pixel while pixmap

is used for images with multiple bits per pixel

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 21

Shape Drawable in XML

This is a generic shape defined in XML

File location

resdrawablefilenamexml

The filename is used as the resource ID

Compiled resource datatype

Resource pointer to a GradientDrawable

Resource reference

In Java Rdrawablefilename

In XML [package]drawablefilename

Syntax

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=[rectangle | oval | line | ring] gt ltcorners androidradius=integer androidtopLeftRadius=integer androidtopRightRadius=integer androidbottomLeftRadius=integer androidbottomRightRadius=integer gt ltgradient androidangle=integer androidcenterX=integer androidcenterY=integer androidcenterColor=integer androidendColor=color androidgradientRadius=integer androidstartColor=color androidtype=[linear | radial | sweep] androidusesLevel=[true | false] gt ltpadding androidleft=integer androidtop=integer androidright=integer androidbottom=integer gt ltsize androidwidth=integer androidheight=integer gt ltsolid

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 22

androidcolor=color gt ltstroke androidwidth=integer androidcolor=color androiddashWidth=integer androiddashGap=integer gt ltshapegt

Elements

ltshapegt

The shape drawable This must be the root element

Attributes

xmlnsandroid

String Required Defines the XML namespace which must be

httpschemasandroidcomapkresandroid

androidshape

Keyword Defines the type of shape Valid values are

Value Desciption

rectangle A rectangle that fills the containing View This is the default shape

oval An oval shape that fits the dimensions of the containing View

line A horizontal line that spans the width of the containing View This

shape requires the ltstrokegt element to define the width of the line

ring A ring shape

The following attributes are used only when androidshape=ring

androidinnerRadius

Dimension The radius for the inner part of the ring (the hole in the middle)

as a dimension value or dimension resource

androidinnerRadiusRatio

Float The radius for the inner part of the ring expressed as a ratio of the

rings width For instance if androidinnerRadiusRatio=5 then the inner

radius equals the rings width divided by 5 This value is overridden by

androidinnerRadius Default value is 9

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 23

androidthickness

Dimension The thickness of the ring as a dimension value or dimension

resource

androidthicknessRatio

Float The thickness of the ring expressed as a ratio of the rings width For

instance if androidthicknessRatio=2 then the thickness equals the rings

width divided by 2 This value is overridden by androidinnerRadius Default

value is 3

androiduseLevel

Boolean true if this is used as a LevelListDrawable This should normally

be false or your shape may not appear

ltcornersgt

Creates rounded corners for the shape Applies only when the shape is a

rectangle

Attributes

androidradius

Dimension The radius for all corners as a dimension value or dimension

resource This is overridden for each corner by the following attributes

androidtopLeftRadius

Dimension The radius for the top-left corner as a dimension value or

dimension resource

androidtopRightRadius

Dimension The radius for the top-right corner as a dimension value or

dimension resource

androidbottomLeftRadius

Dimension The radius for the bottom-left corner as a dimension value or

dimension resource

androidbottomRightRadius

Dimension The radius for the bottom-right corner as a dimension value or

dimension resource

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 24

Note Every corner must (initially) be provided a corner radius greater than

1 or else no corners are rounded If you want specific corners to not be rounded a work-around is to use androidradius to set a default corner

radius greater than 1 but then override each and every corner with the values you really want providing zero (0dp) where you dont want rounded

corners

ltgradientgt

Specifies a gradient color for the shape

Attributes

androidangle

Integer The angle for the gradient in degrees 0 is left to right 90 is bottom

to top It must be a multiple of 45 Default is 0

androidcenterX

Float The relative X-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterY

Float The relative Y-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterColor

Color Optional color that comes between the start and end colors as a

hexadecimal value or color resource

androidendColor

Color The ending color as a hexadecimal value or color resource

androidgradientRadius

Float The radius for the gradient Only applied when androidtype=radial

androidstartColor

Color The starting color as a hexadecimal value or color resource

androidtype

Keyword The type of gradient pattern to apply Valid values are

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 25

Value Description

linear A linear gradient This is the default

radial A radial gradient The start color is the center color

sweep A sweeping line gradient

androiduseLevel

Boolean true if this is used as a LevelListDrawable

ltpaddinggt

Padding to apply to the containing View element (this pads the position of

the View content not the shape)

Attributes

androidleft

Dimension Left padding as a dimension value or dimension resource

androidtop

Dimension Top padding as a dimension value or dimension resource

androidright

Dimension Right padding as a dimension value or dimension resource

androidbottom

Dimension Bottom padding as a dimension value or dimension resource

ltsizegt

The size of the shape

Attributes

androidheight

Dimension The height of the shape as a dimension value or dimension

resource

androidwidth

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 26

Dimension The width of the shape as a dimension value or dimension

resource

Note The shape scales to the size of the container View proportionate to the

dimensions defined here by default When you use the shape in an ImageView you can restrict scaling by setting the androidscaleType to center

ltsolidgt

A solid color to fill the shape

Attributes

androidcolor

Color The color to apply to the shape as a hexadecimal value or color

resource

ltstrokegt

A stroke line for the shape

Attributes

androidwidth

Dimension The thickness of the line as a dimension value or dimension

resource

androidcolor

Color The color of the line as a hexadecimal value or color resource

androiddashGap

Dimension The distance between line dashes as a dimension value or

dimension resource Only valid if androiddashWidth is set

androiddashWidth

Dimension The size of each dash line as a dimension value or dimension

resource Only valid if androiddashGap is set

Example

XML file saved at resdrawablegradient_boxxml

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 27

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=rectanglegt ltgradient androidstartColor=FFFF0000 androidendColor=80FF00FF androidangle=45gt ltpadding androidleft=7dp androidtop=7dp androidright=7dp androidbottom=7dp gt ltcorners androidradius=8dp gt ltshapegt

This layout XML applies the shape drawable to a View

ltTextView androidbackground=drawablegradient_box androidlayout_height=wrap_content androidlayout_width=wrap_content gt

This application code gets the shape drawable and applies it to a View

Resources res = getResources() Drawable shape = res getDrawable(Rdrawablegradient_box)

TextView tv = (TextView)findViewByID(Ridtextview) tvsetBackground(shape)

Page 12: Android graphics mca 5th

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 12

int

getTextWidths(CharSequence text int start int end float[]

widths)

Return the advance widths for the characters in the string

int getTextWidths(String text int start int end float[] widths)

Return the advance widths for the characters in the string

int getTextWidths(char[] text int index int count float[] widths)

Return the advance widths for the characters in the string

Typeface getTypeface()

Get the paints typeface object

final boolean

isAntiAlias()

Helper for getFlags() returning true if ANTI_ALIAS_FLAG bit is

set AntiAliasing smooths out the edges of what is being

drawn but is has no impact on the interior of the shape

final boolean

isStrikeThruText()

Helper for getFlags() returning true if

STRIKE_THRU_TEXT_FLAG bit is set

final boolean

isSubpixelText()

Helper for getFlags() returning true if SUBPIXEL_TEXT_FLAG

bit is set

final boolean

isUnderlineText()

Helper for getFlags() returning true if

UNDERLINE_TEXT_FLAG bit is set

float measureText(String text)

Return the width of the text

float measureText(CharSequence text int start int end)

Return the width of the text

float measureText(String text int start int end)

Return the width of the text

float measureText(char[] text int index int count)

Return the width of the text

void reset()

Restores the paint to its default settings

void set(Paint src)

Copy the fields from src into this paint

void

setARGB(int a int r int g int b)

Helper to setColor() that takes argb and constructs the

color int

void setAlpha(int a)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 13

Helper to setColor() that only assigns the colors alpha value

leaving its rgb values unchanged

void

setAntiAlias(boolean aa)

Helper for setFlags() setting or clearing the ANTI_ALIAS_FLAG

bit AntiAliasing smooths out the edges of what is being drawn

but is has no impact on the interior of the shape

void setColor(int color)

Set the paints color

ColorFilter setColorFilter(ColorFilter filter)

Set or clear the paints colorfilter returning the parameter

void

setFakeBoldText(boolean fakeBoldText)

Helper for setFlags() setting or clearing the

FAKE_BOLD_TEXT_FLAG bit

void setFlags(int flags)

Set the paints flags

PathEffect setPathEffect(PathEffect effect)

Set or clear the patheffect object

Shader setShader(Shader shader)

Set or clear the shader object

void

setShadowLayer(float radius float dx float dy int color)

This draws a shadow layer below the main layer with the

specified offset and color and blur radius

void

setStrikeThruText(boolean strikeThruText)

Helper for setFlags() setting or clearing the

STRIKE_THRU_TEXT_FLAG bit

void

setStyle(PaintStyle style)

Set the paints style used for controlling how primitives

geometries are interpreted (except for drawBitmap which

always assumes Fill)

void

setSubpixelText(boolean subpixelText)

Helper for setFlags() setting or clearing the

SUBPIXEL_TEXT_FLAG bit

void setTextAlign(PaintAlign align)

Set the paints text alignment

void setTextSize(float textSize)

Set the paints text size

void setTextSkewX(float skewX)

Set the paints horizontal skew factor for text

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 14

Typeface setTypeface(Typeface typeface)

Set or clear the typeface object

void

setUnderlineText(boolean underlineText)

Helper for setFlags() setting or clearing the

UNDERLINE_TEXT_FLAG bit

Types of Gradient

1 Linear Gradient

public LinearGradient (float x0 float y0 float x1 float y1 int[] colors float[]

positions ShaderTileMode tile)

Create a shader that draws a linear gradient along a line

Parameters

x0 The x-coordinate for the start of the gradient line

y0 The y-coordinate for the start of the gradient line

x1 The x-coordinate for the end of the gradient line

y1 The y-coordinate for the end of the gradient line

colors The colors to be distributed along the gradient line

positions

May be null The relative positions [01] of each corresponding color in

the colors array If this is null the the colors are distributed evenly

along the gradient line

tile The Shader tiling mode

2 Sweep Gradient

public SweepGradient (float cx float cy int[] colors float[] positions)

A subclass of Shader that draws a sweep gradient around a center point

Parameters

cx The x-coordinate of the center

cy The y-coordinate of the center

colors The colors to be distributed between around the center There must be

at least 2 colors in the array

positions

May be NULL The relative position of each corresponding color in the

colors array beginning with 0 and ending with 10 If the values are not

monotonic the drawing may produce unexpected results If positions is

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 15

NULL then the colors are automatically spaced evenly

3 Radial Gradient

public RadialGradient (float x float y float radius int[] colors float[] positions

ShaderTileMode tile)

Create a shader that draws a radial gradient given the center and radius

Parameters

x The x-coordinate of the center of the radius

y The y-coordinate of the center of the radius

radius Must be positive The radius of the circle for this gradient

colors The colors to be distributed between the center and edge of the circle

positions

May be NULL The relative position of each corresponding color in the

colors array If this is NULL the the colors are distributed evenly

between the center and edge of the circle

tile The Shader tiling mode

Shader Class

Shader is the based class for objects that return horizontal spans of colors during

drawing A subclass of Shader is installed in a Paint calling

paintsetShader(shader) After that any object (other than a bitmap) that is drawn

with that paint will get its color(s) from the shader

ShaderTileMode CLAMP replicate the edge color if the shader draws

outside of its original bounds

ShaderTileMode MIRROR repeat the shaders image horizontally and

vertically alternating mirror images so that adjacent images always seam

ShaderTileMode REPEAT repeat the shaders image horizontally and

vertically

Color

The Color class defines methods for creating and converting color ints Colors are

represented as packed ints made up of 4 bytes alpha red green blue The

values are unpremultiplied meaning any transparency is stored solely in the

alpha component and not in the color components The components are stored as

follows (alpha ltlt 24) | (red ltlt 16) | (green ltlt 8) | blue Each component ranges

between 0255 with 0 meaning no contribution for that component and 255

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 16

meaning 100 contribution Thus opaque-black would be 0xFF000000 (100

opaque but no contributions from red green or blue) and opaque-white would be

0xFFFFFFFF

Constant

int BLACK int LTGRAY

int BLUE int MAGENTA

int CYAN int RED

int DKGRAY int TRANSPARENT

int GRAY int WHITE

int GREEN int YELLOW

Public Constructors

Color()

Public Methods

static int HSVToColor(float[] hsv)

Convert HSV components to an ARGB color

static int HSVToColor(int alpha float[] hsv)

Convert HSV components to an ARGB color

static void RGBToHSV(int red int green int blue float[] hsv)

Convert RGB components to HSV

static int alpha(int color)

Return the alpha component of a color int

static int argb(int alpha int red int green int blue)

Return a color-int from alpha red green blue components

static int blue(int color)

Return the blue component of a color int

static void colorToHSV(int color float[] hsv)

Convert the argb color to its HSV components

static int green(int color)

Return the green component of a color int

static int parseColor(String colorString)

Parse the color string and return the corresponding color-int

static int red(int color)

Return the red component of a color int

static int rgb(int red int green int blue)

Return a color-int from red green blue components

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 17

Working with Text

Android provide several default fonts typeface and styles Application can also use

custom fonts by including font files as application assets and loading them using

the AssetManger same as recourses

Typeface class

The Typeface class specifies the typeface and intrinsic style of a font This is used

in the paint along with optionally Paint settings like textSize textSkewX

textScaleX to specify how text appears when drawn (and measured)

Constant

int BOLD

int BOLD_ITALIC

int ITALIC

int NORMAL

Fields

public static

final Typeface DEFAULT The default NORMAL typeface object

public static

final Typeface DEFAULT_BOLD The default BOLD typeface object

public static

final Typeface MONOSPACE The NORMAL style of the default monospace typeface

public static

final Typeface SANS_SERIF The NORMAL style of the default sans serif typeface

public static

final Typeface SERIF The NORMAL style of the default serif typeface

Public Methods

static

Typeface

create(String familyName int style)

Create a typeface object given a family name and option style

information

static

Typeface

create(Typeface family int style)

Create a typeface object that best matches the specified existing typeface

and the specified Style

static

Typeface

createFromAsset(AssetManager mgr String path)

Create a new typeface from the specified font data

static

Typeface

createFromFile(String path)

Create a new typeface from the specified font file

static createFromFile(File path)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 18

Typeface Create a new typeface from the specified font file

static

Typeface

defaultFromStyle(int style)

Returns one of the default typeface objects based on the specified style

int getStyle()

Returns the typefaces intrinsic style attributes

final

boolean

isBold()

Returns true if getStyle() has the BOLD bit set

final

boolean

isItalic()

Returns true if getStyle() has the ITALIC bit set

Using Default Fonts and Typefaces

By default Android uses the Sans Serif typeface but Monospace and Serif

typefaces are also available The following code excerpt draws some antialiased text in the default typeface (Sans Serif) to a Canvas

import androidgraphicsCanvas import androidgraphicsColor import androidgraphicsPaint import androidgraphicsTypeface Paint mPaint = new Paint(PaintANTI_ALIAS_FLAG) Typeface mType mPaintsetTextSize(16) mPaintsetTypeface(null) canvasdrawText(ldquoDefault Typefacerdquo 20 20 mPaint) You can instead load a different typeface such as Monotype

Typeface mType = Typefacecreate(TypefaceMONOSPACE TypefaceNORMAL) Perhaps you would prefer italic text in which case you can simply set the style of the typeface and the font family

Typeface mType = Typefacecreate(TypefaceSERIF TypefaceITALIC)

You can set certain properties of a typeface such as antialiasing underlining and strikethrough using the setFlags() method of the Paint object

mPaintsetFlags(PaintUNDERLINE_TEXT_FLAG)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 19

Loading Custom typeface from asset

Typeface mType = TypefacecreateFromAsset(getContext()getAssets()ldquofontschess1ttfrdquo) Example ViewFontjava

package compritesh

import androidcontentContext import androidgraphicsCanvas import androidgraphicsColor import androidgraphicsPaint import androidgraphicsTypeface import androidviewView public class ViewFont extends View Context c public ViewFont(Context context) super(context) c=context protected void onDraw(Canvas canvas) Typeface mType = TypefacecreateFromAsset( cgetAssets() fontsBaroqueScriptttf) Paint p =new Paint(PaintANTI_ALIAS_FLAG) psetTypeface(mType) psetTextSize(20) canvasdrawColor(ColorBLUE) canvasdrawText(Welcome to Android canvasgetWidth()4 canvasgetHeight()3 p)

SampleCustomFontjava package compritesh import androidappActivity import androidgraphicsTypeface import androidosBundle public class SampleCustomFont extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain) setContentView(new ViewFont(this))

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 20

Working with Bitmap and Matrix Bitmap

In computer graphics a bitmap or pixmap is a type of memory organization

or image file format used to store digital images The term bitmap comes from the

computer programming terminology meaning just a map of bits a spatially mapped array of bits Now along with pixmap it commonly refers to the similar

concept of a spatially mapped array of pixels Raster images in general may be referred to as bitmaps or pixmaps whether synthetic or photographic in files or

memory In certain contexts the term bitmap implies one bit per pixel while pixmap

is used for images with multiple bits per pixel

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 21

Shape Drawable in XML

This is a generic shape defined in XML

File location

resdrawablefilenamexml

The filename is used as the resource ID

Compiled resource datatype

Resource pointer to a GradientDrawable

Resource reference

In Java Rdrawablefilename

In XML [package]drawablefilename

Syntax

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=[rectangle | oval | line | ring] gt ltcorners androidradius=integer androidtopLeftRadius=integer androidtopRightRadius=integer androidbottomLeftRadius=integer androidbottomRightRadius=integer gt ltgradient androidangle=integer androidcenterX=integer androidcenterY=integer androidcenterColor=integer androidendColor=color androidgradientRadius=integer androidstartColor=color androidtype=[linear | radial | sweep] androidusesLevel=[true | false] gt ltpadding androidleft=integer androidtop=integer androidright=integer androidbottom=integer gt ltsize androidwidth=integer androidheight=integer gt ltsolid

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 22

androidcolor=color gt ltstroke androidwidth=integer androidcolor=color androiddashWidth=integer androiddashGap=integer gt ltshapegt

Elements

ltshapegt

The shape drawable This must be the root element

Attributes

xmlnsandroid

String Required Defines the XML namespace which must be

httpschemasandroidcomapkresandroid

androidshape

Keyword Defines the type of shape Valid values are

Value Desciption

rectangle A rectangle that fills the containing View This is the default shape

oval An oval shape that fits the dimensions of the containing View

line A horizontal line that spans the width of the containing View This

shape requires the ltstrokegt element to define the width of the line

ring A ring shape

The following attributes are used only when androidshape=ring

androidinnerRadius

Dimension The radius for the inner part of the ring (the hole in the middle)

as a dimension value or dimension resource

androidinnerRadiusRatio

Float The radius for the inner part of the ring expressed as a ratio of the

rings width For instance if androidinnerRadiusRatio=5 then the inner

radius equals the rings width divided by 5 This value is overridden by

androidinnerRadius Default value is 9

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 23

androidthickness

Dimension The thickness of the ring as a dimension value or dimension

resource

androidthicknessRatio

Float The thickness of the ring expressed as a ratio of the rings width For

instance if androidthicknessRatio=2 then the thickness equals the rings

width divided by 2 This value is overridden by androidinnerRadius Default

value is 3

androiduseLevel

Boolean true if this is used as a LevelListDrawable This should normally

be false or your shape may not appear

ltcornersgt

Creates rounded corners for the shape Applies only when the shape is a

rectangle

Attributes

androidradius

Dimension The radius for all corners as a dimension value or dimension

resource This is overridden for each corner by the following attributes

androidtopLeftRadius

Dimension The radius for the top-left corner as a dimension value or

dimension resource

androidtopRightRadius

Dimension The radius for the top-right corner as a dimension value or

dimension resource

androidbottomLeftRadius

Dimension The radius for the bottom-left corner as a dimension value or

dimension resource

androidbottomRightRadius

Dimension The radius for the bottom-right corner as a dimension value or

dimension resource

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 24

Note Every corner must (initially) be provided a corner radius greater than

1 or else no corners are rounded If you want specific corners to not be rounded a work-around is to use androidradius to set a default corner

radius greater than 1 but then override each and every corner with the values you really want providing zero (0dp) where you dont want rounded

corners

ltgradientgt

Specifies a gradient color for the shape

Attributes

androidangle

Integer The angle for the gradient in degrees 0 is left to right 90 is bottom

to top It must be a multiple of 45 Default is 0

androidcenterX

Float The relative X-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterY

Float The relative Y-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterColor

Color Optional color that comes between the start and end colors as a

hexadecimal value or color resource

androidendColor

Color The ending color as a hexadecimal value or color resource

androidgradientRadius

Float The radius for the gradient Only applied when androidtype=radial

androidstartColor

Color The starting color as a hexadecimal value or color resource

androidtype

Keyword The type of gradient pattern to apply Valid values are

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 25

Value Description

linear A linear gradient This is the default

radial A radial gradient The start color is the center color

sweep A sweeping line gradient

androiduseLevel

Boolean true if this is used as a LevelListDrawable

ltpaddinggt

Padding to apply to the containing View element (this pads the position of

the View content not the shape)

Attributes

androidleft

Dimension Left padding as a dimension value or dimension resource

androidtop

Dimension Top padding as a dimension value or dimension resource

androidright

Dimension Right padding as a dimension value or dimension resource

androidbottom

Dimension Bottom padding as a dimension value or dimension resource

ltsizegt

The size of the shape

Attributes

androidheight

Dimension The height of the shape as a dimension value or dimension

resource

androidwidth

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 26

Dimension The width of the shape as a dimension value or dimension

resource

Note The shape scales to the size of the container View proportionate to the

dimensions defined here by default When you use the shape in an ImageView you can restrict scaling by setting the androidscaleType to center

ltsolidgt

A solid color to fill the shape

Attributes

androidcolor

Color The color to apply to the shape as a hexadecimal value or color

resource

ltstrokegt

A stroke line for the shape

Attributes

androidwidth

Dimension The thickness of the line as a dimension value or dimension

resource

androidcolor

Color The color of the line as a hexadecimal value or color resource

androiddashGap

Dimension The distance between line dashes as a dimension value or

dimension resource Only valid if androiddashWidth is set

androiddashWidth

Dimension The size of each dash line as a dimension value or dimension

resource Only valid if androiddashGap is set

Example

XML file saved at resdrawablegradient_boxxml

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 27

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=rectanglegt ltgradient androidstartColor=FFFF0000 androidendColor=80FF00FF androidangle=45gt ltpadding androidleft=7dp androidtop=7dp androidright=7dp androidbottom=7dp gt ltcorners androidradius=8dp gt ltshapegt

This layout XML applies the shape drawable to a View

ltTextView androidbackground=drawablegradient_box androidlayout_height=wrap_content androidlayout_width=wrap_content gt

This application code gets the shape drawable and applies it to a View

Resources res = getResources() Drawable shape = res getDrawable(Rdrawablegradient_box)

TextView tv = (TextView)findViewByID(Ridtextview) tvsetBackground(shape)

Page 13: Android graphics mca 5th

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 13

Helper to setColor() that only assigns the colors alpha value

leaving its rgb values unchanged

void

setAntiAlias(boolean aa)

Helper for setFlags() setting or clearing the ANTI_ALIAS_FLAG

bit AntiAliasing smooths out the edges of what is being drawn

but is has no impact on the interior of the shape

void setColor(int color)

Set the paints color

ColorFilter setColorFilter(ColorFilter filter)

Set or clear the paints colorfilter returning the parameter

void

setFakeBoldText(boolean fakeBoldText)

Helper for setFlags() setting or clearing the

FAKE_BOLD_TEXT_FLAG bit

void setFlags(int flags)

Set the paints flags

PathEffect setPathEffect(PathEffect effect)

Set or clear the patheffect object

Shader setShader(Shader shader)

Set or clear the shader object

void

setShadowLayer(float radius float dx float dy int color)

This draws a shadow layer below the main layer with the

specified offset and color and blur radius

void

setStrikeThruText(boolean strikeThruText)

Helper for setFlags() setting or clearing the

STRIKE_THRU_TEXT_FLAG bit

void

setStyle(PaintStyle style)

Set the paints style used for controlling how primitives

geometries are interpreted (except for drawBitmap which

always assumes Fill)

void

setSubpixelText(boolean subpixelText)

Helper for setFlags() setting or clearing the

SUBPIXEL_TEXT_FLAG bit

void setTextAlign(PaintAlign align)

Set the paints text alignment

void setTextSize(float textSize)

Set the paints text size

void setTextSkewX(float skewX)

Set the paints horizontal skew factor for text

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 14

Typeface setTypeface(Typeface typeface)

Set or clear the typeface object

void

setUnderlineText(boolean underlineText)

Helper for setFlags() setting or clearing the

UNDERLINE_TEXT_FLAG bit

Types of Gradient

1 Linear Gradient

public LinearGradient (float x0 float y0 float x1 float y1 int[] colors float[]

positions ShaderTileMode tile)

Create a shader that draws a linear gradient along a line

Parameters

x0 The x-coordinate for the start of the gradient line

y0 The y-coordinate for the start of the gradient line

x1 The x-coordinate for the end of the gradient line

y1 The y-coordinate for the end of the gradient line

colors The colors to be distributed along the gradient line

positions

May be null The relative positions [01] of each corresponding color in

the colors array If this is null the the colors are distributed evenly

along the gradient line

tile The Shader tiling mode

2 Sweep Gradient

public SweepGradient (float cx float cy int[] colors float[] positions)

A subclass of Shader that draws a sweep gradient around a center point

Parameters

cx The x-coordinate of the center

cy The y-coordinate of the center

colors The colors to be distributed between around the center There must be

at least 2 colors in the array

positions

May be NULL The relative position of each corresponding color in the

colors array beginning with 0 and ending with 10 If the values are not

monotonic the drawing may produce unexpected results If positions is

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 15

NULL then the colors are automatically spaced evenly

3 Radial Gradient

public RadialGradient (float x float y float radius int[] colors float[] positions

ShaderTileMode tile)

Create a shader that draws a radial gradient given the center and radius

Parameters

x The x-coordinate of the center of the radius

y The y-coordinate of the center of the radius

radius Must be positive The radius of the circle for this gradient

colors The colors to be distributed between the center and edge of the circle

positions

May be NULL The relative position of each corresponding color in the

colors array If this is NULL the the colors are distributed evenly

between the center and edge of the circle

tile The Shader tiling mode

Shader Class

Shader is the based class for objects that return horizontal spans of colors during

drawing A subclass of Shader is installed in a Paint calling

paintsetShader(shader) After that any object (other than a bitmap) that is drawn

with that paint will get its color(s) from the shader

ShaderTileMode CLAMP replicate the edge color if the shader draws

outside of its original bounds

ShaderTileMode MIRROR repeat the shaders image horizontally and

vertically alternating mirror images so that adjacent images always seam

ShaderTileMode REPEAT repeat the shaders image horizontally and

vertically

Color

The Color class defines methods for creating and converting color ints Colors are

represented as packed ints made up of 4 bytes alpha red green blue The

values are unpremultiplied meaning any transparency is stored solely in the

alpha component and not in the color components The components are stored as

follows (alpha ltlt 24) | (red ltlt 16) | (green ltlt 8) | blue Each component ranges

between 0255 with 0 meaning no contribution for that component and 255

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 16

meaning 100 contribution Thus opaque-black would be 0xFF000000 (100

opaque but no contributions from red green or blue) and opaque-white would be

0xFFFFFFFF

Constant

int BLACK int LTGRAY

int BLUE int MAGENTA

int CYAN int RED

int DKGRAY int TRANSPARENT

int GRAY int WHITE

int GREEN int YELLOW

Public Constructors

Color()

Public Methods

static int HSVToColor(float[] hsv)

Convert HSV components to an ARGB color

static int HSVToColor(int alpha float[] hsv)

Convert HSV components to an ARGB color

static void RGBToHSV(int red int green int blue float[] hsv)

Convert RGB components to HSV

static int alpha(int color)

Return the alpha component of a color int

static int argb(int alpha int red int green int blue)

Return a color-int from alpha red green blue components

static int blue(int color)

Return the blue component of a color int

static void colorToHSV(int color float[] hsv)

Convert the argb color to its HSV components

static int green(int color)

Return the green component of a color int

static int parseColor(String colorString)

Parse the color string and return the corresponding color-int

static int red(int color)

Return the red component of a color int

static int rgb(int red int green int blue)

Return a color-int from red green blue components

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 17

Working with Text

Android provide several default fonts typeface and styles Application can also use

custom fonts by including font files as application assets and loading them using

the AssetManger same as recourses

Typeface class

The Typeface class specifies the typeface and intrinsic style of a font This is used

in the paint along with optionally Paint settings like textSize textSkewX

textScaleX to specify how text appears when drawn (and measured)

Constant

int BOLD

int BOLD_ITALIC

int ITALIC

int NORMAL

Fields

public static

final Typeface DEFAULT The default NORMAL typeface object

public static

final Typeface DEFAULT_BOLD The default BOLD typeface object

public static

final Typeface MONOSPACE The NORMAL style of the default monospace typeface

public static

final Typeface SANS_SERIF The NORMAL style of the default sans serif typeface

public static

final Typeface SERIF The NORMAL style of the default serif typeface

Public Methods

static

Typeface

create(String familyName int style)

Create a typeface object given a family name and option style

information

static

Typeface

create(Typeface family int style)

Create a typeface object that best matches the specified existing typeface

and the specified Style

static

Typeface

createFromAsset(AssetManager mgr String path)

Create a new typeface from the specified font data

static

Typeface

createFromFile(String path)

Create a new typeface from the specified font file

static createFromFile(File path)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 18

Typeface Create a new typeface from the specified font file

static

Typeface

defaultFromStyle(int style)

Returns one of the default typeface objects based on the specified style

int getStyle()

Returns the typefaces intrinsic style attributes

final

boolean

isBold()

Returns true if getStyle() has the BOLD bit set

final

boolean

isItalic()

Returns true if getStyle() has the ITALIC bit set

Using Default Fonts and Typefaces

By default Android uses the Sans Serif typeface but Monospace and Serif

typefaces are also available The following code excerpt draws some antialiased text in the default typeface (Sans Serif) to a Canvas

import androidgraphicsCanvas import androidgraphicsColor import androidgraphicsPaint import androidgraphicsTypeface Paint mPaint = new Paint(PaintANTI_ALIAS_FLAG) Typeface mType mPaintsetTextSize(16) mPaintsetTypeface(null) canvasdrawText(ldquoDefault Typefacerdquo 20 20 mPaint) You can instead load a different typeface such as Monotype

Typeface mType = Typefacecreate(TypefaceMONOSPACE TypefaceNORMAL) Perhaps you would prefer italic text in which case you can simply set the style of the typeface and the font family

Typeface mType = Typefacecreate(TypefaceSERIF TypefaceITALIC)

You can set certain properties of a typeface such as antialiasing underlining and strikethrough using the setFlags() method of the Paint object

mPaintsetFlags(PaintUNDERLINE_TEXT_FLAG)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 19

Loading Custom typeface from asset

Typeface mType = TypefacecreateFromAsset(getContext()getAssets()ldquofontschess1ttfrdquo) Example ViewFontjava

package compritesh

import androidcontentContext import androidgraphicsCanvas import androidgraphicsColor import androidgraphicsPaint import androidgraphicsTypeface import androidviewView public class ViewFont extends View Context c public ViewFont(Context context) super(context) c=context protected void onDraw(Canvas canvas) Typeface mType = TypefacecreateFromAsset( cgetAssets() fontsBaroqueScriptttf) Paint p =new Paint(PaintANTI_ALIAS_FLAG) psetTypeface(mType) psetTextSize(20) canvasdrawColor(ColorBLUE) canvasdrawText(Welcome to Android canvasgetWidth()4 canvasgetHeight()3 p)

SampleCustomFontjava package compritesh import androidappActivity import androidgraphicsTypeface import androidosBundle public class SampleCustomFont extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain) setContentView(new ViewFont(this))

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 20

Working with Bitmap and Matrix Bitmap

In computer graphics a bitmap or pixmap is a type of memory organization

or image file format used to store digital images The term bitmap comes from the

computer programming terminology meaning just a map of bits a spatially mapped array of bits Now along with pixmap it commonly refers to the similar

concept of a spatially mapped array of pixels Raster images in general may be referred to as bitmaps or pixmaps whether synthetic or photographic in files or

memory In certain contexts the term bitmap implies one bit per pixel while pixmap

is used for images with multiple bits per pixel

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 21

Shape Drawable in XML

This is a generic shape defined in XML

File location

resdrawablefilenamexml

The filename is used as the resource ID

Compiled resource datatype

Resource pointer to a GradientDrawable

Resource reference

In Java Rdrawablefilename

In XML [package]drawablefilename

Syntax

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=[rectangle | oval | line | ring] gt ltcorners androidradius=integer androidtopLeftRadius=integer androidtopRightRadius=integer androidbottomLeftRadius=integer androidbottomRightRadius=integer gt ltgradient androidangle=integer androidcenterX=integer androidcenterY=integer androidcenterColor=integer androidendColor=color androidgradientRadius=integer androidstartColor=color androidtype=[linear | radial | sweep] androidusesLevel=[true | false] gt ltpadding androidleft=integer androidtop=integer androidright=integer androidbottom=integer gt ltsize androidwidth=integer androidheight=integer gt ltsolid

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 22

androidcolor=color gt ltstroke androidwidth=integer androidcolor=color androiddashWidth=integer androiddashGap=integer gt ltshapegt

Elements

ltshapegt

The shape drawable This must be the root element

Attributes

xmlnsandroid

String Required Defines the XML namespace which must be

httpschemasandroidcomapkresandroid

androidshape

Keyword Defines the type of shape Valid values are

Value Desciption

rectangle A rectangle that fills the containing View This is the default shape

oval An oval shape that fits the dimensions of the containing View

line A horizontal line that spans the width of the containing View This

shape requires the ltstrokegt element to define the width of the line

ring A ring shape

The following attributes are used only when androidshape=ring

androidinnerRadius

Dimension The radius for the inner part of the ring (the hole in the middle)

as a dimension value or dimension resource

androidinnerRadiusRatio

Float The radius for the inner part of the ring expressed as a ratio of the

rings width For instance if androidinnerRadiusRatio=5 then the inner

radius equals the rings width divided by 5 This value is overridden by

androidinnerRadius Default value is 9

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 23

androidthickness

Dimension The thickness of the ring as a dimension value or dimension

resource

androidthicknessRatio

Float The thickness of the ring expressed as a ratio of the rings width For

instance if androidthicknessRatio=2 then the thickness equals the rings

width divided by 2 This value is overridden by androidinnerRadius Default

value is 3

androiduseLevel

Boolean true if this is used as a LevelListDrawable This should normally

be false or your shape may not appear

ltcornersgt

Creates rounded corners for the shape Applies only when the shape is a

rectangle

Attributes

androidradius

Dimension The radius for all corners as a dimension value or dimension

resource This is overridden for each corner by the following attributes

androidtopLeftRadius

Dimension The radius for the top-left corner as a dimension value or

dimension resource

androidtopRightRadius

Dimension The radius for the top-right corner as a dimension value or

dimension resource

androidbottomLeftRadius

Dimension The radius for the bottom-left corner as a dimension value or

dimension resource

androidbottomRightRadius

Dimension The radius for the bottom-right corner as a dimension value or

dimension resource

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 24

Note Every corner must (initially) be provided a corner radius greater than

1 or else no corners are rounded If you want specific corners to not be rounded a work-around is to use androidradius to set a default corner

radius greater than 1 but then override each and every corner with the values you really want providing zero (0dp) where you dont want rounded

corners

ltgradientgt

Specifies a gradient color for the shape

Attributes

androidangle

Integer The angle for the gradient in degrees 0 is left to right 90 is bottom

to top It must be a multiple of 45 Default is 0

androidcenterX

Float The relative X-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterY

Float The relative Y-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterColor

Color Optional color that comes between the start and end colors as a

hexadecimal value or color resource

androidendColor

Color The ending color as a hexadecimal value or color resource

androidgradientRadius

Float The radius for the gradient Only applied when androidtype=radial

androidstartColor

Color The starting color as a hexadecimal value or color resource

androidtype

Keyword The type of gradient pattern to apply Valid values are

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 25

Value Description

linear A linear gradient This is the default

radial A radial gradient The start color is the center color

sweep A sweeping line gradient

androiduseLevel

Boolean true if this is used as a LevelListDrawable

ltpaddinggt

Padding to apply to the containing View element (this pads the position of

the View content not the shape)

Attributes

androidleft

Dimension Left padding as a dimension value or dimension resource

androidtop

Dimension Top padding as a dimension value or dimension resource

androidright

Dimension Right padding as a dimension value or dimension resource

androidbottom

Dimension Bottom padding as a dimension value or dimension resource

ltsizegt

The size of the shape

Attributes

androidheight

Dimension The height of the shape as a dimension value or dimension

resource

androidwidth

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 26

Dimension The width of the shape as a dimension value or dimension

resource

Note The shape scales to the size of the container View proportionate to the

dimensions defined here by default When you use the shape in an ImageView you can restrict scaling by setting the androidscaleType to center

ltsolidgt

A solid color to fill the shape

Attributes

androidcolor

Color The color to apply to the shape as a hexadecimal value or color

resource

ltstrokegt

A stroke line for the shape

Attributes

androidwidth

Dimension The thickness of the line as a dimension value or dimension

resource

androidcolor

Color The color of the line as a hexadecimal value or color resource

androiddashGap

Dimension The distance between line dashes as a dimension value or

dimension resource Only valid if androiddashWidth is set

androiddashWidth

Dimension The size of each dash line as a dimension value or dimension

resource Only valid if androiddashGap is set

Example

XML file saved at resdrawablegradient_boxxml

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 27

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=rectanglegt ltgradient androidstartColor=FFFF0000 androidendColor=80FF00FF androidangle=45gt ltpadding androidleft=7dp androidtop=7dp androidright=7dp androidbottom=7dp gt ltcorners androidradius=8dp gt ltshapegt

This layout XML applies the shape drawable to a View

ltTextView androidbackground=drawablegradient_box androidlayout_height=wrap_content androidlayout_width=wrap_content gt

This application code gets the shape drawable and applies it to a View

Resources res = getResources() Drawable shape = res getDrawable(Rdrawablegradient_box)

TextView tv = (TextView)findViewByID(Ridtextview) tvsetBackground(shape)

Page 14: Android graphics mca 5th

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 14

Typeface setTypeface(Typeface typeface)

Set or clear the typeface object

void

setUnderlineText(boolean underlineText)

Helper for setFlags() setting or clearing the

UNDERLINE_TEXT_FLAG bit

Types of Gradient

1 Linear Gradient

public LinearGradient (float x0 float y0 float x1 float y1 int[] colors float[]

positions ShaderTileMode tile)

Create a shader that draws a linear gradient along a line

Parameters

x0 The x-coordinate for the start of the gradient line

y0 The y-coordinate for the start of the gradient line

x1 The x-coordinate for the end of the gradient line

y1 The y-coordinate for the end of the gradient line

colors The colors to be distributed along the gradient line

positions

May be null The relative positions [01] of each corresponding color in

the colors array If this is null the the colors are distributed evenly

along the gradient line

tile The Shader tiling mode

2 Sweep Gradient

public SweepGradient (float cx float cy int[] colors float[] positions)

A subclass of Shader that draws a sweep gradient around a center point

Parameters

cx The x-coordinate of the center

cy The y-coordinate of the center

colors The colors to be distributed between around the center There must be

at least 2 colors in the array

positions

May be NULL The relative position of each corresponding color in the

colors array beginning with 0 and ending with 10 If the values are not

monotonic the drawing may produce unexpected results If positions is

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 15

NULL then the colors are automatically spaced evenly

3 Radial Gradient

public RadialGradient (float x float y float radius int[] colors float[] positions

ShaderTileMode tile)

Create a shader that draws a radial gradient given the center and radius

Parameters

x The x-coordinate of the center of the radius

y The y-coordinate of the center of the radius

radius Must be positive The radius of the circle for this gradient

colors The colors to be distributed between the center and edge of the circle

positions

May be NULL The relative position of each corresponding color in the

colors array If this is NULL the the colors are distributed evenly

between the center and edge of the circle

tile The Shader tiling mode

Shader Class

Shader is the based class for objects that return horizontal spans of colors during

drawing A subclass of Shader is installed in a Paint calling

paintsetShader(shader) After that any object (other than a bitmap) that is drawn

with that paint will get its color(s) from the shader

ShaderTileMode CLAMP replicate the edge color if the shader draws

outside of its original bounds

ShaderTileMode MIRROR repeat the shaders image horizontally and

vertically alternating mirror images so that adjacent images always seam

ShaderTileMode REPEAT repeat the shaders image horizontally and

vertically

Color

The Color class defines methods for creating and converting color ints Colors are

represented as packed ints made up of 4 bytes alpha red green blue The

values are unpremultiplied meaning any transparency is stored solely in the

alpha component and not in the color components The components are stored as

follows (alpha ltlt 24) | (red ltlt 16) | (green ltlt 8) | blue Each component ranges

between 0255 with 0 meaning no contribution for that component and 255

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 16

meaning 100 contribution Thus opaque-black would be 0xFF000000 (100

opaque but no contributions from red green or blue) and opaque-white would be

0xFFFFFFFF

Constant

int BLACK int LTGRAY

int BLUE int MAGENTA

int CYAN int RED

int DKGRAY int TRANSPARENT

int GRAY int WHITE

int GREEN int YELLOW

Public Constructors

Color()

Public Methods

static int HSVToColor(float[] hsv)

Convert HSV components to an ARGB color

static int HSVToColor(int alpha float[] hsv)

Convert HSV components to an ARGB color

static void RGBToHSV(int red int green int blue float[] hsv)

Convert RGB components to HSV

static int alpha(int color)

Return the alpha component of a color int

static int argb(int alpha int red int green int blue)

Return a color-int from alpha red green blue components

static int blue(int color)

Return the blue component of a color int

static void colorToHSV(int color float[] hsv)

Convert the argb color to its HSV components

static int green(int color)

Return the green component of a color int

static int parseColor(String colorString)

Parse the color string and return the corresponding color-int

static int red(int color)

Return the red component of a color int

static int rgb(int red int green int blue)

Return a color-int from red green blue components

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 17

Working with Text

Android provide several default fonts typeface and styles Application can also use

custom fonts by including font files as application assets and loading them using

the AssetManger same as recourses

Typeface class

The Typeface class specifies the typeface and intrinsic style of a font This is used

in the paint along with optionally Paint settings like textSize textSkewX

textScaleX to specify how text appears when drawn (and measured)

Constant

int BOLD

int BOLD_ITALIC

int ITALIC

int NORMAL

Fields

public static

final Typeface DEFAULT The default NORMAL typeface object

public static

final Typeface DEFAULT_BOLD The default BOLD typeface object

public static

final Typeface MONOSPACE The NORMAL style of the default monospace typeface

public static

final Typeface SANS_SERIF The NORMAL style of the default sans serif typeface

public static

final Typeface SERIF The NORMAL style of the default serif typeface

Public Methods

static

Typeface

create(String familyName int style)

Create a typeface object given a family name and option style

information

static

Typeface

create(Typeface family int style)

Create a typeface object that best matches the specified existing typeface

and the specified Style

static

Typeface

createFromAsset(AssetManager mgr String path)

Create a new typeface from the specified font data

static

Typeface

createFromFile(String path)

Create a new typeface from the specified font file

static createFromFile(File path)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 18

Typeface Create a new typeface from the specified font file

static

Typeface

defaultFromStyle(int style)

Returns one of the default typeface objects based on the specified style

int getStyle()

Returns the typefaces intrinsic style attributes

final

boolean

isBold()

Returns true if getStyle() has the BOLD bit set

final

boolean

isItalic()

Returns true if getStyle() has the ITALIC bit set

Using Default Fonts and Typefaces

By default Android uses the Sans Serif typeface but Monospace and Serif

typefaces are also available The following code excerpt draws some antialiased text in the default typeface (Sans Serif) to a Canvas

import androidgraphicsCanvas import androidgraphicsColor import androidgraphicsPaint import androidgraphicsTypeface Paint mPaint = new Paint(PaintANTI_ALIAS_FLAG) Typeface mType mPaintsetTextSize(16) mPaintsetTypeface(null) canvasdrawText(ldquoDefault Typefacerdquo 20 20 mPaint) You can instead load a different typeface such as Monotype

Typeface mType = Typefacecreate(TypefaceMONOSPACE TypefaceNORMAL) Perhaps you would prefer italic text in which case you can simply set the style of the typeface and the font family

Typeface mType = Typefacecreate(TypefaceSERIF TypefaceITALIC)

You can set certain properties of a typeface such as antialiasing underlining and strikethrough using the setFlags() method of the Paint object

mPaintsetFlags(PaintUNDERLINE_TEXT_FLAG)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 19

Loading Custom typeface from asset

Typeface mType = TypefacecreateFromAsset(getContext()getAssets()ldquofontschess1ttfrdquo) Example ViewFontjava

package compritesh

import androidcontentContext import androidgraphicsCanvas import androidgraphicsColor import androidgraphicsPaint import androidgraphicsTypeface import androidviewView public class ViewFont extends View Context c public ViewFont(Context context) super(context) c=context protected void onDraw(Canvas canvas) Typeface mType = TypefacecreateFromAsset( cgetAssets() fontsBaroqueScriptttf) Paint p =new Paint(PaintANTI_ALIAS_FLAG) psetTypeface(mType) psetTextSize(20) canvasdrawColor(ColorBLUE) canvasdrawText(Welcome to Android canvasgetWidth()4 canvasgetHeight()3 p)

SampleCustomFontjava package compritesh import androidappActivity import androidgraphicsTypeface import androidosBundle public class SampleCustomFont extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain) setContentView(new ViewFont(this))

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 20

Working with Bitmap and Matrix Bitmap

In computer graphics a bitmap or pixmap is a type of memory organization

or image file format used to store digital images The term bitmap comes from the

computer programming terminology meaning just a map of bits a spatially mapped array of bits Now along with pixmap it commonly refers to the similar

concept of a spatially mapped array of pixels Raster images in general may be referred to as bitmaps or pixmaps whether synthetic or photographic in files or

memory In certain contexts the term bitmap implies one bit per pixel while pixmap

is used for images with multiple bits per pixel

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 21

Shape Drawable in XML

This is a generic shape defined in XML

File location

resdrawablefilenamexml

The filename is used as the resource ID

Compiled resource datatype

Resource pointer to a GradientDrawable

Resource reference

In Java Rdrawablefilename

In XML [package]drawablefilename

Syntax

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=[rectangle | oval | line | ring] gt ltcorners androidradius=integer androidtopLeftRadius=integer androidtopRightRadius=integer androidbottomLeftRadius=integer androidbottomRightRadius=integer gt ltgradient androidangle=integer androidcenterX=integer androidcenterY=integer androidcenterColor=integer androidendColor=color androidgradientRadius=integer androidstartColor=color androidtype=[linear | radial | sweep] androidusesLevel=[true | false] gt ltpadding androidleft=integer androidtop=integer androidright=integer androidbottom=integer gt ltsize androidwidth=integer androidheight=integer gt ltsolid

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 22

androidcolor=color gt ltstroke androidwidth=integer androidcolor=color androiddashWidth=integer androiddashGap=integer gt ltshapegt

Elements

ltshapegt

The shape drawable This must be the root element

Attributes

xmlnsandroid

String Required Defines the XML namespace which must be

httpschemasandroidcomapkresandroid

androidshape

Keyword Defines the type of shape Valid values are

Value Desciption

rectangle A rectangle that fills the containing View This is the default shape

oval An oval shape that fits the dimensions of the containing View

line A horizontal line that spans the width of the containing View This

shape requires the ltstrokegt element to define the width of the line

ring A ring shape

The following attributes are used only when androidshape=ring

androidinnerRadius

Dimension The radius for the inner part of the ring (the hole in the middle)

as a dimension value or dimension resource

androidinnerRadiusRatio

Float The radius for the inner part of the ring expressed as a ratio of the

rings width For instance if androidinnerRadiusRatio=5 then the inner

radius equals the rings width divided by 5 This value is overridden by

androidinnerRadius Default value is 9

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 23

androidthickness

Dimension The thickness of the ring as a dimension value or dimension

resource

androidthicknessRatio

Float The thickness of the ring expressed as a ratio of the rings width For

instance if androidthicknessRatio=2 then the thickness equals the rings

width divided by 2 This value is overridden by androidinnerRadius Default

value is 3

androiduseLevel

Boolean true if this is used as a LevelListDrawable This should normally

be false or your shape may not appear

ltcornersgt

Creates rounded corners for the shape Applies only when the shape is a

rectangle

Attributes

androidradius

Dimension The radius for all corners as a dimension value or dimension

resource This is overridden for each corner by the following attributes

androidtopLeftRadius

Dimension The radius for the top-left corner as a dimension value or

dimension resource

androidtopRightRadius

Dimension The radius for the top-right corner as a dimension value or

dimension resource

androidbottomLeftRadius

Dimension The radius for the bottom-left corner as a dimension value or

dimension resource

androidbottomRightRadius

Dimension The radius for the bottom-right corner as a dimension value or

dimension resource

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 24

Note Every corner must (initially) be provided a corner radius greater than

1 or else no corners are rounded If you want specific corners to not be rounded a work-around is to use androidradius to set a default corner

radius greater than 1 but then override each and every corner with the values you really want providing zero (0dp) where you dont want rounded

corners

ltgradientgt

Specifies a gradient color for the shape

Attributes

androidangle

Integer The angle for the gradient in degrees 0 is left to right 90 is bottom

to top It must be a multiple of 45 Default is 0

androidcenterX

Float The relative X-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterY

Float The relative Y-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterColor

Color Optional color that comes between the start and end colors as a

hexadecimal value or color resource

androidendColor

Color The ending color as a hexadecimal value or color resource

androidgradientRadius

Float The radius for the gradient Only applied when androidtype=radial

androidstartColor

Color The starting color as a hexadecimal value or color resource

androidtype

Keyword The type of gradient pattern to apply Valid values are

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 25

Value Description

linear A linear gradient This is the default

radial A radial gradient The start color is the center color

sweep A sweeping line gradient

androiduseLevel

Boolean true if this is used as a LevelListDrawable

ltpaddinggt

Padding to apply to the containing View element (this pads the position of

the View content not the shape)

Attributes

androidleft

Dimension Left padding as a dimension value or dimension resource

androidtop

Dimension Top padding as a dimension value or dimension resource

androidright

Dimension Right padding as a dimension value or dimension resource

androidbottom

Dimension Bottom padding as a dimension value or dimension resource

ltsizegt

The size of the shape

Attributes

androidheight

Dimension The height of the shape as a dimension value or dimension

resource

androidwidth

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 26

Dimension The width of the shape as a dimension value or dimension

resource

Note The shape scales to the size of the container View proportionate to the

dimensions defined here by default When you use the shape in an ImageView you can restrict scaling by setting the androidscaleType to center

ltsolidgt

A solid color to fill the shape

Attributes

androidcolor

Color The color to apply to the shape as a hexadecimal value or color

resource

ltstrokegt

A stroke line for the shape

Attributes

androidwidth

Dimension The thickness of the line as a dimension value or dimension

resource

androidcolor

Color The color of the line as a hexadecimal value or color resource

androiddashGap

Dimension The distance between line dashes as a dimension value or

dimension resource Only valid if androiddashWidth is set

androiddashWidth

Dimension The size of each dash line as a dimension value or dimension

resource Only valid if androiddashGap is set

Example

XML file saved at resdrawablegradient_boxxml

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 27

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=rectanglegt ltgradient androidstartColor=FFFF0000 androidendColor=80FF00FF androidangle=45gt ltpadding androidleft=7dp androidtop=7dp androidright=7dp androidbottom=7dp gt ltcorners androidradius=8dp gt ltshapegt

This layout XML applies the shape drawable to a View

ltTextView androidbackground=drawablegradient_box androidlayout_height=wrap_content androidlayout_width=wrap_content gt

This application code gets the shape drawable and applies it to a View

Resources res = getResources() Drawable shape = res getDrawable(Rdrawablegradient_box)

TextView tv = (TextView)findViewByID(Ridtextview) tvsetBackground(shape)

Page 15: Android graphics mca 5th

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 15

NULL then the colors are automatically spaced evenly

3 Radial Gradient

public RadialGradient (float x float y float radius int[] colors float[] positions

ShaderTileMode tile)

Create a shader that draws a radial gradient given the center and radius

Parameters

x The x-coordinate of the center of the radius

y The y-coordinate of the center of the radius

radius Must be positive The radius of the circle for this gradient

colors The colors to be distributed between the center and edge of the circle

positions

May be NULL The relative position of each corresponding color in the

colors array If this is NULL the the colors are distributed evenly

between the center and edge of the circle

tile The Shader tiling mode

Shader Class

Shader is the based class for objects that return horizontal spans of colors during

drawing A subclass of Shader is installed in a Paint calling

paintsetShader(shader) After that any object (other than a bitmap) that is drawn

with that paint will get its color(s) from the shader

ShaderTileMode CLAMP replicate the edge color if the shader draws

outside of its original bounds

ShaderTileMode MIRROR repeat the shaders image horizontally and

vertically alternating mirror images so that adjacent images always seam

ShaderTileMode REPEAT repeat the shaders image horizontally and

vertically

Color

The Color class defines methods for creating and converting color ints Colors are

represented as packed ints made up of 4 bytes alpha red green blue The

values are unpremultiplied meaning any transparency is stored solely in the

alpha component and not in the color components The components are stored as

follows (alpha ltlt 24) | (red ltlt 16) | (green ltlt 8) | blue Each component ranges

between 0255 with 0 meaning no contribution for that component and 255

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 16

meaning 100 contribution Thus opaque-black would be 0xFF000000 (100

opaque but no contributions from red green or blue) and opaque-white would be

0xFFFFFFFF

Constant

int BLACK int LTGRAY

int BLUE int MAGENTA

int CYAN int RED

int DKGRAY int TRANSPARENT

int GRAY int WHITE

int GREEN int YELLOW

Public Constructors

Color()

Public Methods

static int HSVToColor(float[] hsv)

Convert HSV components to an ARGB color

static int HSVToColor(int alpha float[] hsv)

Convert HSV components to an ARGB color

static void RGBToHSV(int red int green int blue float[] hsv)

Convert RGB components to HSV

static int alpha(int color)

Return the alpha component of a color int

static int argb(int alpha int red int green int blue)

Return a color-int from alpha red green blue components

static int blue(int color)

Return the blue component of a color int

static void colorToHSV(int color float[] hsv)

Convert the argb color to its HSV components

static int green(int color)

Return the green component of a color int

static int parseColor(String colorString)

Parse the color string and return the corresponding color-int

static int red(int color)

Return the red component of a color int

static int rgb(int red int green int blue)

Return a color-int from red green blue components

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 17

Working with Text

Android provide several default fonts typeface and styles Application can also use

custom fonts by including font files as application assets and loading them using

the AssetManger same as recourses

Typeface class

The Typeface class specifies the typeface and intrinsic style of a font This is used

in the paint along with optionally Paint settings like textSize textSkewX

textScaleX to specify how text appears when drawn (and measured)

Constant

int BOLD

int BOLD_ITALIC

int ITALIC

int NORMAL

Fields

public static

final Typeface DEFAULT The default NORMAL typeface object

public static

final Typeface DEFAULT_BOLD The default BOLD typeface object

public static

final Typeface MONOSPACE The NORMAL style of the default monospace typeface

public static

final Typeface SANS_SERIF The NORMAL style of the default sans serif typeface

public static

final Typeface SERIF The NORMAL style of the default serif typeface

Public Methods

static

Typeface

create(String familyName int style)

Create a typeface object given a family name and option style

information

static

Typeface

create(Typeface family int style)

Create a typeface object that best matches the specified existing typeface

and the specified Style

static

Typeface

createFromAsset(AssetManager mgr String path)

Create a new typeface from the specified font data

static

Typeface

createFromFile(String path)

Create a new typeface from the specified font file

static createFromFile(File path)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 18

Typeface Create a new typeface from the specified font file

static

Typeface

defaultFromStyle(int style)

Returns one of the default typeface objects based on the specified style

int getStyle()

Returns the typefaces intrinsic style attributes

final

boolean

isBold()

Returns true if getStyle() has the BOLD bit set

final

boolean

isItalic()

Returns true if getStyle() has the ITALIC bit set

Using Default Fonts and Typefaces

By default Android uses the Sans Serif typeface but Monospace and Serif

typefaces are also available The following code excerpt draws some antialiased text in the default typeface (Sans Serif) to a Canvas

import androidgraphicsCanvas import androidgraphicsColor import androidgraphicsPaint import androidgraphicsTypeface Paint mPaint = new Paint(PaintANTI_ALIAS_FLAG) Typeface mType mPaintsetTextSize(16) mPaintsetTypeface(null) canvasdrawText(ldquoDefault Typefacerdquo 20 20 mPaint) You can instead load a different typeface such as Monotype

Typeface mType = Typefacecreate(TypefaceMONOSPACE TypefaceNORMAL) Perhaps you would prefer italic text in which case you can simply set the style of the typeface and the font family

Typeface mType = Typefacecreate(TypefaceSERIF TypefaceITALIC)

You can set certain properties of a typeface such as antialiasing underlining and strikethrough using the setFlags() method of the Paint object

mPaintsetFlags(PaintUNDERLINE_TEXT_FLAG)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 19

Loading Custom typeface from asset

Typeface mType = TypefacecreateFromAsset(getContext()getAssets()ldquofontschess1ttfrdquo) Example ViewFontjava

package compritesh

import androidcontentContext import androidgraphicsCanvas import androidgraphicsColor import androidgraphicsPaint import androidgraphicsTypeface import androidviewView public class ViewFont extends View Context c public ViewFont(Context context) super(context) c=context protected void onDraw(Canvas canvas) Typeface mType = TypefacecreateFromAsset( cgetAssets() fontsBaroqueScriptttf) Paint p =new Paint(PaintANTI_ALIAS_FLAG) psetTypeface(mType) psetTextSize(20) canvasdrawColor(ColorBLUE) canvasdrawText(Welcome to Android canvasgetWidth()4 canvasgetHeight()3 p)

SampleCustomFontjava package compritesh import androidappActivity import androidgraphicsTypeface import androidosBundle public class SampleCustomFont extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain) setContentView(new ViewFont(this))

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 20

Working with Bitmap and Matrix Bitmap

In computer graphics a bitmap or pixmap is a type of memory organization

or image file format used to store digital images The term bitmap comes from the

computer programming terminology meaning just a map of bits a spatially mapped array of bits Now along with pixmap it commonly refers to the similar

concept of a spatially mapped array of pixels Raster images in general may be referred to as bitmaps or pixmaps whether synthetic or photographic in files or

memory In certain contexts the term bitmap implies one bit per pixel while pixmap

is used for images with multiple bits per pixel

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 21

Shape Drawable in XML

This is a generic shape defined in XML

File location

resdrawablefilenamexml

The filename is used as the resource ID

Compiled resource datatype

Resource pointer to a GradientDrawable

Resource reference

In Java Rdrawablefilename

In XML [package]drawablefilename

Syntax

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=[rectangle | oval | line | ring] gt ltcorners androidradius=integer androidtopLeftRadius=integer androidtopRightRadius=integer androidbottomLeftRadius=integer androidbottomRightRadius=integer gt ltgradient androidangle=integer androidcenterX=integer androidcenterY=integer androidcenterColor=integer androidendColor=color androidgradientRadius=integer androidstartColor=color androidtype=[linear | radial | sweep] androidusesLevel=[true | false] gt ltpadding androidleft=integer androidtop=integer androidright=integer androidbottom=integer gt ltsize androidwidth=integer androidheight=integer gt ltsolid

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 22

androidcolor=color gt ltstroke androidwidth=integer androidcolor=color androiddashWidth=integer androiddashGap=integer gt ltshapegt

Elements

ltshapegt

The shape drawable This must be the root element

Attributes

xmlnsandroid

String Required Defines the XML namespace which must be

httpschemasandroidcomapkresandroid

androidshape

Keyword Defines the type of shape Valid values are

Value Desciption

rectangle A rectangle that fills the containing View This is the default shape

oval An oval shape that fits the dimensions of the containing View

line A horizontal line that spans the width of the containing View This

shape requires the ltstrokegt element to define the width of the line

ring A ring shape

The following attributes are used only when androidshape=ring

androidinnerRadius

Dimension The radius for the inner part of the ring (the hole in the middle)

as a dimension value or dimension resource

androidinnerRadiusRatio

Float The radius for the inner part of the ring expressed as a ratio of the

rings width For instance if androidinnerRadiusRatio=5 then the inner

radius equals the rings width divided by 5 This value is overridden by

androidinnerRadius Default value is 9

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 23

androidthickness

Dimension The thickness of the ring as a dimension value or dimension

resource

androidthicknessRatio

Float The thickness of the ring expressed as a ratio of the rings width For

instance if androidthicknessRatio=2 then the thickness equals the rings

width divided by 2 This value is overridden by androidinnerRadius Default

value is 3

androiduseLevel

Boolean true if this is used as a LevelListDrawable This should normally

be false or your shape may not appear

ltcornersgt

Creates rounded corners for the shape Applies only when the shape is a

rectangle

Attributes

androidradius

Dimension The radius for all corners as a dimension value or dimension

resource This is overridden for each corner by the following attributes

androidtopLeftRadius

Dimension The radius for the top-left corner as a dimension value or

dimension resource

androidtopRightRadius

Dimension The radius for the top-right corner as a dimension value or

dimension resource

androidbottomLeftRadius

Dimension The radius for the bottom-left corner as a dimension value or

dimension resource

androidbottomRightRadius

Dimension The radius for the bottom-right corner as a dimension value or

dimension resource

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 24

Note Every corner must (initially) be provided a corner radius greater than

1 or else no corners are rounded If you want specific corners to not be rounded a work-around is to use androidradius to set a default corner

radius greater than 1 but then override each and every corner with the values you really want providing zero (0dp) where you dont want rounded

corners

ltgradientgt

Specifies a gradient color for the shape

Attributes

androidangle

Integer The angle for the gradient in degrees 0 is left to right 90 is bottom

to top It must be a multiple of 45 Default is 0

androidcenterX

Float The relative X-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterY

Float The relative Y-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterColor

Color Optional color that comes between the start and end colors as a

hexadecimal value or color resource

androidendColor

Color The ending color as a hexadecimal value or color resource

androidgradientRadius

Float The radius for the gradient Only applied when androidtype=radial

androidstartColor

Color The starting color as a hexadecimal value or color resource

androidtype

Keyword The type of gradient pattern to apply Valid values are

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 25

Value Description

linear A linear gradient This is the default

radial A radial gradient The start color is the center color

sweep A sweeping line gradient

androiduseLevel

Boolean true if this is used as a LevelListDrawable

ltpaddinggt

Padding to apply to the containing View element (this pads the position of

the View content not the shape)

Attributes

androidleft

Dimension Left padding as a dimension value or dimension resource

androidtop

Dimension Top padding as a dimension value or dimension resource

androidright

Dimension Right padding as a dimension value or dimension resource

androidbottom

Dimension Bottom padding as a dimension value or dimension resource

ltsizegt

The size of the shape

Attributes

androidheight

Dimension The height of the shape as a dimension value or dimension

resource

androidwidth

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 26

Dimension The width of the shape as a dimension value or dimension

resource

Note The shape scales to the size of the container View proportionate to the

dimensions defined here by default When you use the shape in an ImageView you can restrict scaling by setting the androidscaleType to center

ltsolidgt

A solid color to fill the shape

Attributes

androidcolor

Color The color to apply to the shape as a hexadecimal value or color

resource

ltstrokegt

A stroke line for the shape

Attributes

androidwidth

Dimension The thickness of the line as a dimension value or dimension

resource

androidcolor

Color The color of the line as a hexadecimal value or color resource

androiddashGap

Dimension The distance between line dashes as a dimension value or

dimension resource Only valid if androiddashWidth is set

androiddashWidth

Dimension The size of each dash line as a dimension value or dimension

resource Only valid if androiddashGap is set

Example

XML file saved at resdrawablegradient_boxxml

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 27

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=rectanglegt ltgradient androidstartColor=FFFF0000 androidendColor=80FF00FF androidangle=45gt ltpadding androidleft=7dp androidtop=7dp androidright=7dp androidbottom=7dp gt ltcorners androidradius=8dp gt ltshapegt

This layout XML applies the shape drawable to a View

ltTextView androidbackground=drawablegradient_box androidlayout_height=wrap_content androidlayout_width=wrap_content gt

This application code gets the shape drawable and applies it to a View

Resources res = getResources() Drawable shape = res getDrawable(Rdrawablegradient_box)

TextView tv = (TextView)findViewByID(Ridtextview) tvsetBackground(shape)

Page 16: Android graphics mca 5th

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 16

meaning 100 contribution Thus opaque-black would be 0xFF000000 (100

opaque but no contributions from red green or blue) and opaque-white would be

0xFFFFFFFF

Constant

int BLACK int LTGRAY

int BLUE int MAGENTA

int CYAN int RED

int DKGRAY int TRANSPARENT

int GRAY int WHITE

int GREEN int YELLOW

Public Constructors

Color()

Public Methods

static int HSVToColor(float[] hsv)

Convert HSV components to an ARGB color

static int HSVToColor(int alpha float[] hsv)

Convert HSV components to an ARGB color

static void RGBToHSV(int red int green int blue float[] hsv)

Convert RGB components to HSV

static int alpha(int color)

Return the alpha component of a color int

static int argb(int alpha int red int green int blue)

Return a color-int from alpha red green blue components

static int blue(int color)

Return the blue component of a color int

static void colorToHSV(int color float[] hsv)

Convert the argb color to its HSV components

static int green(int color)

Return the green component of a color int

static int parseColor(String colorString)

Parse the color string and return the corresponding color-int

static int red(int color)

Return the red component of a color int

static int rgb(int red int green int blue)

Return a color-int from red green blue components

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 17

Working with Text

Android provide several default fonts typeface and styles Application can also use

custom fonts by including font files as application assets and loading them using

the AssetManger same as recourses

Typeface class

The Typeface class specifies the typeface and intrinsic style of a font This is used

in the paint along with optionally Paint settings like textSize textSkewX

textScaleX to specify how text appears when drawn (and measured)

Constant

int BOLD

int BOLD_ITALIC

int ITALIC

int NORMAL

Fields

public static

final Typeface DEFAULT The default NORMAL typeface object

public static

final Typeface DEFAULT_BOLD The default BOLD typeface object

public static

final Typeface MONOSPACE The NORMAL style of the default monospace typeface

public static

final Typeface SANS_SERIF The NORMAL style of the default sans serif typeface

public static

final Typeface SERIF The NORMAL style of the default serif typeface

Public Methods

static

Typeface

create(String familyName int style)

Create a typeface object given a family name and option style

information

static

Typeface

create(Typeface family int style)

Create a typeface object that best matches the specified existing typeface

and the specified Style

static

Typeface

createFromAsset(AssetManager mgr String path)

Create a new typeface from the specified font data

static

Typeface

createFromFile(String path)

Create a new typeface from the specified font file

static createFromFile(File path)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 18

Typeface Create a new typeface from the specified font file

static

Typeface

defaultFromStyle(int style)

Returns one of the default typeface objects based on the specified style

int getStyle()

Returns the typefaces intrinsic style attributes

final

boolean

isBold()

Returns true if getStyle() has the BOLD bit set

final

boolean

isItalic()

Returns true if getStyle() has the ITALIC bit set

Using Default Fonts and Typefaces

By default Android uses the Sans Serif typeface but Monospace and Serif

typefaces are also available The following code excerpt draws some antialiased text in the default typeface (Sans Serif) to a Canvas

import androidgraphicsCanvas import androidgraphicsColor import androidgraphicsPaint import androidgraphicsTypeface Paint mPaint = new Paint(PaintANTI_ALIAS_FLAG) Typeface mType mPaintsetTextSize(16) mPaintsetTypeface(null) canvasdrawText(ldquoDefault Typefacerdquo 20 20 mPaint) You can instead load a different typeface such as Monotype

Typeface mType = Typefacecreate(TypefaceMONOSPACE TypefaceNORMAL) Perhaps you would prefer italic text in which case you can simply set the style of the typeface and the font family

Typeface mType = Typefacecreate(TypefaceSERIF TypefaceITALIC)

You can set certain properties of a typeface such as antialiasing underlining and strikethrough using the setFlags() method of the Paint object

mPaintsetFlags(PaintUNDERLINE_TEXT_FLAG)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 19

Loading Custom typeface from asset

Typeface mType = TypefacecreateFromAsset(getContext()getAssets()ldquofontschess1ttfrdquo) Example ViewFontjava

package compritesh

import androidcontentContext import androidgraphicsCanvas import androidgraphicsColor import androidgraphicsPaint import androidgraphicsTypeface import androidviewView public class ViewFont extends View Context c public ViewFont(Context context) super(context) c=context protected void onDraw(Canvas canvas) Typeface mType = TypefacecreateFromAsset( cgetAssets() fontsBaroqueScriptttf) Paint p =new Paint(PaintANTI_ALIAS_FLAG) psetTypeface(mType) psetTextSize(20) canvasdrawColor(ColorBLUE) canvasdrawText(Welcome to Android canvasgetWidth()4 canvasgetHeight()3 p)

SampleCustomFontjava package compritesh import androidappActivity import androidgraphicsTypeface import androidosBundle public class SampleCustomFont extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain) setContentView(new ViewFont(this))

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 20

Working with Bitmap and Matrix Bitmap

In computer graphics a bitmap or pixmap is a type of memory organization

or image file format used to store digital images The term bitmap comes from the

computer programming terminology meaning just a map of bits a spatially mapped array of bits Now along with pixmap it commonly refers to the similar

concept of a spatially mapped array of pixels Raster images in general may be referred to as bitmaps or pixmaps whether synthetic or photographic in files or

memory In certain contexts the term bitmap implies one bit per pixel while pixmap

is used for images with multiple bits per pixel

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 21

Shape Drawable in XML

This is a generic shape defined in XML

File location

resdrawablefilenamexml

The filename is used as the resource ID

Compiled resource datatype

Resource pointer to a GradientDrawable

Resource reference

In Java Rdrawablefilename

In XML [package]drawablefilename

Syntax

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=[rectangle | oval | line | ring] gt ltcorners androidradius=integer androidtopLeftRadius=integer androidtopRightRadius=integer androidbottomLeftRadius=integer androidbottomRightRadius=integer gt ltgradient androidangle=integer androidcenterX=integer androidcenterY=integer androidcenterColor=integer androidendColor=color androidgradientRadius=integer androidstartColor=color androidtype=[linear | radial | sweep] androidusesLevel=[true | false] gt ltpadding androidleft=integer androidtop=integer androidright=integer androidbottom=integer gt ltsize androidwidth=integer androidheight=integer gt ltsolid

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 22

androidcolor=color gt ltstroke androidwidth=integer androidcolor=color androiddashWidth=integer androiddashGap=integer gt ltshapegt

Elements

ltshapegt

The shape drawable This must be the root element

Attributes

xmlnsandroid

String Required Defines the XML namespace which must be

httpschemasandroidcomapkresandroid

androidshape

Keyword Defines the type of shape Valid values are

Value Desciption

rectangle A rectangle that fills the containing View This is the default shape

oval An oval shape that fits the dimensions of the containing View

line A horizontal line that spans the width of the containing View This

shape requires the ltstrokegt element to define the width of the line

ring A ring shape

The following attributes are used only when androidshape=ring

androidinnerRadius

Dimension The radius for the inner part of the ring (the hole in the middle)

as a dimension value or dimension resource

androidinnerRadiusRatio

Float The radius for the inner part of the ring expressed as a ratio of the

rings width For instance if androidinnerRadiusRatio=5 then the inner

radius equals the rings width divided by 5 This value is overridden by

androidinnerRadius Default value is 9

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 23

androidthickness

Dimension The thickness of the ring as a dimension value or dimension

resource

androidthicknessRatio

Float The thickness of the ring expressed as a ratio of the rings width For

instance if androidthicknessRatio=2 then the thickness equals the rings

width divided by 2 This value is overridden by androidinnerRadius Default

value is 3

androiduseLevel

Boolean true if this is used as a LevelListDrawable This should normally

be false or your shape may not appear

ltcornersgt

Creates rounded corners for the shape Applies only when the shape is a

rectangle

Attributes

androidradius

Dimension The radius for all corners as a dimension value or dimension

resource This is overridden for each corner by the following attributes

androidtopLeftRadius

Dimension The radius for the top-left corner as a dimension value or

dimension resource

androidtopRightRadius

Dimension The radius for the top-right corner as a dimension value or

dimension resource

androidbottomLeftRadius

Dimension The radius for the bottom-left corner as a dimension value or

dimension resource

androidbottomRightRadius

Dimension The radius for the bottom-right corner as a dimension value or

dimension resource

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 24

Note Every corner must (initially) be provided a corner radius greater than

1 or else no corners are rounded If you want specific corners to not be rounded a work-around is to use androidradius to set a default corner

radius greater than 1 but then override each and every corner with the values you really want providing zero (0dp) where you dont want rounded

corners

ltgradientgt

Specifies a gradient color for the shape

Attributes

androidangle

Integer The angle for the gradient in degrees 0 is left to right 90 is bottom

to top It must be a multiple of 45 Default is 0

androidcenterX

Float The relative X-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterY

Float The relative Y-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterColor

Color Optional color that comes between the start and end colors as a

hexadecimal value or color resource

androidendColor

Color The ending color as a hexadecimal value or color resource

androidgradientRadius

Float The radius for the gradient Only applied when androidtype=radial

androidstartColor

Color The starting color as a hexadecimal value or color resource

androidtype

Keyword The type of gradient pattern to apply Valid values are

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 25

Value Description

linear A linear gradient This is the default

radial A radial gradient The start color is the center color

sweep A sweeping line gradient

androiduseLevel

Boolean true if this is used as a LevelListDrawable

ltpaddinggt

Padding to apply to the containing View element (this pads the position of

the View content not the shape)

Attributes

androidleft

Dimension Left padding as a dimension value or dimension resource

androidtop

Dimension Top padding as a dimension value or dimension resource

androidright

Dimension Right padding as a dimension value or dimension resource

androidbottom

Dimension Bottom padding as a dimension value or dimension resource

ltsizegt

The size of the shape

Attributes

androidheight

Dimension The height of the shape as a dimension value or dimension

resource

androidwidth

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 26

Dimension The width of the shape as a dimension value or dimension

resource

Note The shape scales to the size of the container View proportionate to the

dimensions defined here by default When you use the shape in an ImageView you can restrict scaling by setting the androidscaleType to center

ltsolidgt

A solid color to fill the shape

Attributes

androidcolor

Color The color to apply to the shape as a hexadecimal value or color

resource

ltstrokegt

A stroke line for the shape

Attributes

androidwidth

Dimension The thickness of the line as a dimension value or dimension

resource

androidcolor

Color The color of the line as a hexadecimal value or color resource

androiddashGap

Dimension The distance between line dashes as a dimension value or

dimension resource Only valid if androiddashWidth is set

androiddashWidth

Dimension The size of each dash line as a dimension value or dimension

resource Only valid if androiddashGap is set

Example

XML file saved at resdrawablegradient_boxxml

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 27

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=rectanglegt ltgradient androidstartColor=FFFF0000 androidendColor=80FF00FF androidangle=45gt ltpadding androidleft=7dp androidtop=7dp androidright=7dp androidbottom=7dp gt ltcorners androidradius=8dp gt ltshapegt

This layout XML applies the shape drawable to a View

ltTextView androidbackground=drawablegradient_box androidlayout_height=wrap_content androidlayout_width=wrap_content gt

This application code gets the shape drawable and applies it to a View

Resources res = getResources() Drawable shape = res getDrawable(Rdrawablegradient_box)

TextView tv = (TextView)findViewByID(Ridtextview) tvsetBackground(shape)

Page 17: Android graphics mca 5th

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 17

Working with Text

Android provide several default fonts typeface and styles Application can also use

custom fonts by including font files as application assets and loading them using

the AssetManger same as recourses

Typeface class

The Typeface class specifies the typeface and intrinsic style of a font This is used

in the paint along with optionally Paint settings like textSize textSkewX

textScaleX to specify how text appears when drawn (and measured)

Constant

int BOLD

int BOLD_ITALIC

int ITALIC

int NORMAL

Fields

public static

final Typeface DEFAULT The default NORMAL typeface object

public static

final Typeface DEFAULT_BOLD The default BOLD typeface object

public static

final Typeface MONOSPACE The NORMAL style of the default monospace typeface

public static

final Typeface SANS_SERIF The NORMAL style of the default sans serif typeface

public static

final Typeface SERIF The NORMAL style of the default serif typeface

Public Methods

static

Typeface

create(String familyName int style)

Create a typeface object given a family name and option style

information

static

Typeface

create(Typeface family int style)

Create a typeface object that best matches the specified existing typeface

and the specified Style

static

Typeface

createFromAsset(AssetManager mgr String path)

Create a new typeface from the specified font data

static

Typeface

createFromFile(String path)

Create a new typeface from the specified font file

static createFromFile(File path)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 18

Typeface Create a new typeface from the specified font file

static

Typeface

defaultFromStyle(int style)

Returns one of the default typeface objects based on the specified style

int getStyle()

Returns the typefaces intrinsic style attributes

final

boolean

isBold()

Returns true if getStyle() has the BOLD bit set

final

boolean

isItalic()

Returns true if getStyle() has the ITALIC bit set

Using Default Fonts and Typefaces

By default Android uses the Sans Serif typeface but Monospace and Serif

typefaces are also available The following code excerpt draws some antialiased text in the default typeface (Sans Serif) to a Canvas

import androidgraphicsCanvas import androidgraphicsColor import androidgraphicsPaint import androidgraphicsTypeface Paint mPaint = new Paint(PaintANTI_ALIAS_FLAG) Typeface mType mPaintsetTextSize(16) mPaintsetTypeface(null) canvasdrawText(ldquoDefault Typefacerdquo 20 20 mPaint) You can instead load a different typeface such as Monotype

Typeface mType = Typefacecreate(TypefaceMONOSPACE TypefaceNORMAL) Perhaps you would prefer italic text in which case you can simply set the style of the typeface and the font family

Typeface mType = Typefacecreate(TypefaceSERIF TypefaceITALIC)

You can set certain properties of a typeface such as antialiasing underlining and strikethrough using the setFlags() method of the Paint object

mPaintsetFlags(PaintUNDERLINE_TEXT_FLAG)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 19

Loading Custom typeface from asset

Typeface mType = TypefacecreateFromAsset(getContext()getAssets()ldquofontschess1ttfrdquo) Example ViewFontjava

package compritesh

import androidcontentContext import androidgraphicsCanvas import androidgraphicsColor import androidgraphicsPaint import androidgraphicsTypeface import androidviewView public class ViewFont extends View Context c public ViewFont(Context context) super(context) c=context protected void onDraw(Canvas canvas) Typeface mType = TypefacecreateFromAsset( cgetAssets() fontsBaroqueScriptttf) Paint p =new Paint(PaintANTI_ALIAS_FLAG) psetTypeface(mType) psetTextSize(20) canvasdrawColor(ColorBLUE) canvasdrawText(Welcome to Android canvasgetWidth()4 canvasgetHeight()3 p)

SampleCustomFontjava package compritesh import androidappActivity import androidgraphicsTypeface import androidosBundle public class SampleCustomFont extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain) setContentView(new ViewFont(this))

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 20

Working with Bitmap and Matrix Bitmap

In computer graphics a bitmap or pixmap is a type of memory organization

or image file format used to store digital images The term bitmap comes from the

computer programming terminology meaning just a map of bits a spatially mapped array of bits Now along with pixmap it commonly refers to the similar

concept of a spatially mapped array of pixels Raster images in general may be referred to as bitmaps or pixmaps whether synthetic or photographic in files or

memory In certain contexts the term bitmap implies one bit per pixel while pixmap

is used for images with multiple bits per pixel

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 21

Shape Drawable in XML

This is a generic shape defined in XML

File location

resdrawablefilenamexml

The filename is used as the resource ID

Compiled resource datatype

Resource pointer to a GradientDrawable

Resource reference

In Java Rdrawablefilename

In XML [package]drawablefilename

Syntax

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=[rectangle | oval | line | ring] gt ltcorners androidradius=integer androidtopLeftRadius=integer androidtopRightRadius=integer androidbottomLeftRadius=integer androidbottomRightRadius=integer gt ltgradient androidangle=integer androidcenterX=integer androidcenterY=integer androidcenterColor=integer androidendColor=color androidgradientRadius=integer androidstartColor=color androidtype=[linear | radial | sweep] androidusesLevel=[true | false] gt ltpadding androidleft=integer androidtop=integer androidright=integer androidbottom=integer gt ltsize androidwidth=integer androidheight=integer gt ltsolid

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 22

androidcolor=color gt ltstroke androidwidth=integer androidcolor=color androiddashWidth=integer androiddashGap=integer gt ltshapegt

Elements

ltshapegt

The shape drawable This must be the root element

Attributes

xmlnsandroid

String Required Defines the XML namespace which must be

httpschemasandroidcomapkresandroid

androidshape

Keyword Defines the type of shape Valid values are

Value Desciption

rectangle A rectangle that fills the containing View This is the default shape

oval An oval shape that fits the dimensions of the containing View

line A horizontal line that spans the width of the containing View This

shape requires the ltstrokegt element to define the width of the line

ring A ring shape

The following attributes are used only when androidshape=ring

androidinnerRadius

Dimension The radius for the inner part of the ring (the hole in the middle)

as a dimension value or dimension resource

androidinnerRadiusRatio

Float The radius for the inner part of the ring expressed as a ratio of the

rings width For instance if androidinnerRadiusRatio=5 then the inner

radius equals the rings width divided by 5 This value is overridden by

androidinnerRadius Default value is 9

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 23

androidthickness

Dimension The thickness of the ring as a dimension value or dimension

resource

androidthicknessRatio

Float The thickness of the ring expressed as a ratio of the rings width For

instance if androidthicknessRatio=2 then the thickness equals the rings

width divided by 2 This value is overridden by androidinnerRadius Default

value is 3

androiduseLevel

Boolean true if this is used as a LevelListDrawable This should normally

be false or your shape may not appear

ltcornersgt

Creates rounded corners for the shape Applies only when the shape is a

rectangle

Attributes

androidradius

Dimension The radius for all corners as a dimension value or dimension

resource This is overridden for each corner by the following attributes

androidtopLeftRadius

Dimension The radius for the top-left corner as a dimension value or

dimension resource

androidtopRightRadius

Dimension The radius for the top-right corner as a dimension value or

dimension resource

androidbottomLeftRadius

Dimension The radius for the bottom-left corner as a dimension value or

dimension resource

androidbottomRightRadius

Dimension The radius for the bottom-right corner as a dimension value or

dimension resource

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 24

Note Every corner must (initially) be provided a corner radius greater than

1 or else no corners are rounded If you want specific corners to not be rounded a work-around is to use androidradius to set a default corner

radius greater than 1 but then override each and every corner with the values you really want providing zero (0dp) where you dont want rounded

corners

ltgradientgt

Specifies a gradient color for the shape

Attributes

androidangle

Integer The angle for the gradient in degrees 0 is left to right 90 is bottom

to top It must be a multiple of 45 Default is 0

androidcenterX

Float The relative X-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterY

Float The relative Y-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterColor

Color Optional color that comes between the start and end colors as a

hexadecimal value or color resource

androidendColor

Color The ending color as a hexadecimal value or color resource

androidgradientRadius

Float The radius for the gradient Only applied when androidtype=radial

androidstartColor

Color The starting color as a hexadecimal value or color resource

androidtype

Keyword The type of gradient pattern to apply Valid values are

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 25

Value Description

linear A linear gradient This is the default

radial A radial gradient The start color is the center color

sweep A sweeping line gradient

androiduseLevel

Boolean true if this is used as a LevelListDrawable

ltpaddinggt

Padding to apply to the containing View element (this pads the position of

the View content not the shape)

Attributes

androidleft

Dimension Left padding as a dimension value or dimension resource

androidtop

Dimension Top padding as a dimension value or dimension resource

androidright

Dimension Right padding as a dimension value or dimension resource

androidbottom

Dimension Bottom padding as a dimension value or dimension resource

ltsizegt

The size of the shape

Attributes

androidheight

Dimension The height of the shape as a dimension value or dimension

resource

androidwidth

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 26

Dimension The width of the shape as a dimension value or dimension

resource

Note The shape scales to the size of the container View proportionate to the

dimensions defined here by default When you use the shape in an ImageView you can restrict scaling by setting the androidscaleType to center

ltsolidgt

A solid color to fill the shape

Attributes

androidcolor

Color The color to apply to the shape as a hexadecimal value or color

resource

ltstrokegt

A stroke line for the shape

Attributes

androidwidth

Dimension The thickness of the line as a dimension value or dimension

resource

androidcolor

Color The color of the line as a hexadecimal value or color resource

androiddashGap

Dimension The distance between line dashes as a dimension value or

dimension resource Only valid if androiddashWidth is set

androiddashWidth

Dimension The size of each dash line as a dimension value or dimension

resource Only valid if androiddashGap is set

Example

XML file saved at resdrawablegradient_boxxml

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 27

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=rectanglegt ltgradient androidstartColor=FFFF0000 androidendColor=80FF00FF androidangle=45gt ltpadding androidleft=7dp androidtop=7dp androidright=7dp androidbottom=7dp gt ltcorners androidradius=8dp gt ltshapegt

This layout XML applies the shape drawable to a View

ltTextView androidbackground=drawablegradient_box androidlayout_height=wrap_content androidlayout_width=wrap_content gt

This application code gets the shape drawable and applies it to a View

Resources res = getResources() Drawable shape = res getDrawable(Rdrawablegradient_box)

TextView tv = (TextView)findViewByID(Ridtextview) tvsetBackground(shape)

Page 18: Android graphics mca 5th

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 18

Typeface Create a new typeface from the specified font file

static

Typeface

defaultFromStyle(int style)

Returns one of the default typeface objects based on the specified style

int getStyle()

Returns the typefaces intrinsic style attributes

final

boolean

isBold()

Returns true if getStyle() has the BOLD bit set

final

boolean

isItalic()

Returns true if getStyle() has the ITALIC bit set

Using Default Fonts and Typefaces

By default Android uses the Sans Serif typeface but Monospace and Serif

typefaces are also available The following code excerpt draws some antialiased text in the default typeface (Sans Serif) to a Canvas

import androidgraphicsCanvas import androidgraphicsColor import androidgraphicsPaint import androidgraphicsTypeface Paint mPaint = new Paint(PaintANTI_ALIAS_FLAG) Typeface mType mPaintsetTextSize(16) mPaintsetTypeface(null) canvasdrawText(ldquoDefault Typefacerdquo 20 20 mPaint) You can instead load a different typeface such as Monotype

Typeface mType = Typefacecreate(TypefaceMONOSPACE TypefaceNORMAL) Perhaps you would prefer italic text in which case you can simply set the style of the typeface and the font family

Typeface mType = Typefacecreate(TypefaceSERIF TypefaceITALIC)

You can set certain properties of a typeface such as antialiasing underlining and strikethrough using the setFlags() method of the Paint object

mPaintsetFlags(PaintUNDERLINE_TEXT_FLAG)

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 19

Loading Custom typeface from asset

Typeface mType = TypefacecreateFromAsset(getContext()getAssets()ldquofontschess1ttfrdquo) Example ViewFontjava

package compritesh

import androidcontentContext import androidgraphicsCanvas import androidgraphicsColor import androidgraphicsPaint import androidgraphicsTypeface import androidviewView public class ViewFont extends View Context c public ViewFont(Context context) super(context) c=context protected void onDraw(Canvas canvas) Typeface mType = TypefacecreateFromAsset( cgetAssets() fontsBaroqueScriptttf) Paint p =new Paint(PaintANTI_ALIAS_FLAG) psetTypeface(mType) psetTextSize(20) canvasdrawColor(ColorBLUE) canvasdrawText(Welcome to Android canvasgetWidth()4 canvasgetHeight()3 p)

SampleCustomFontjava package compritesh import androidappActivity import androidgraphicsTypeface import androidosBundle public class SampleCustomFont extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain) setContentView(new ViewFont(this))

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 20

Working with Bitmap and Matrix Bitmap

In computer graphics a bitmap or pixmap is a type of memory organization

or image file format used to store digital images The term bitmap comes from the

computer programming terminology meaning just a map of bits a spatially mapped array of bits Now along with pixmap it commonly refers to the similar

concept of a spatially mapped array of pixels Raster images in general may be referred to as bitmaps or pixmaps whether synthetic or photographic in files or

memory In certain contexts the term bitmap implies one bit per pixel while pixmap

is used for images with multiple bits per pixel

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 21

Shape Drawable in XML

This is a generic shape defined in XML

File location

resdrawablefilenamexml

The filename is used as the resource ID

Compiled resource datatype

Resource pointer to a GradientDrawable

Resource reference

In Java Rdrawablefilename

In XML [package]drawablefilename

Syntax

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=[rectangle | oval | line | ring] gt ltcorners androidradius=integer androidtopLeftRadius=integer androidtopRightRadius=integer androidbottomLeftRadius=integer androidbottomRightRadius=integer gt ltgradient androidangle=integer androidcenterX=integer androidcenterY=integer androidcenterColor=integer androidendColor=color androidgradientRadius=integer androidstartColor=color androidtype=[linear | radial | sweep] androidusesLevel=[true | false] gt ltpadding androidleft=integer androidtop=integer androidright=integer androidbottom=integer gt ltsize androidwidth=integer androidheight=integer gt ltsolid

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 22

androidcolor=color gt ltstroke androidwidth=integer androidcolor=color androiddashWidth=integer androiddashGap=integer gt ltshapegt

Elements

ltshapegt

The shape drawable This must be the root element

Attributes

xmlnsandroid

String Required Defines the XML namespace which must be

httpschemasandroidcomapkresandroid

androidshape

Keyword Defines the type of shape Valid values are

Value Desciption

rectangle A rectangle that fills the containing View This is the default shape

oval An oval shape that fits the dimensions of the containing View

line A horizontal line that spans the width of the containing View This

shape requires the ltstrokegt element to define the width of the line

ring A ring shape

The following attributes are used only when androidshape=ring

androidinnerRadius

Dimension The radius for the inner part of the ring (the hole in the middle)

as a dimension value or dimension resource

androidinnerRadiusRatio

Float The radius for the inner part of the ring expressed as a ratio of the

rings width For instance if androidinnerRadiusRatio=5 then the inner

radius equals the rings width divided by 5 This value is overridden by

androidinnerRadius Default value is 9

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 23

androidthickness

Dimension The thickness of the ring as a dimension value or dimension

resource

androidthicknessRatio

Float The thickness of the ring expressed as a ratio of the rings width For

instance if androidthicknessRatio=2 then the thickness equals the rings

width divided by 2 This value is overridden by androidinnerRadius Default

value is 3

androiduseLevel

Boolean true if this is used as a LevelListDrawable This should normally

be false or your shape may not appear

ltcornersgt

Creates rounded corners for the shape Applies only when the shape is a

rectangle

Attributes

androidradius

Dimension The radius for all corners as a dimension value or dimension

resource This is overridden for each corner by the following attributes

androidtopLeftRadius

Dimension The radius for the top-left corner as a dimension value or

dimension resource

androidtopRightRadius

Dimension The radius for the top-right corner as a dimension value or

dimension resource

androidbottomLeftRadius

Dimension The radius for the bottom-left corner as a dimension value or

dimension resource

androidbottomRightRadius

Dimension The radius for the bottom-right corner as a dimension value or

dimension resource

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 24

Note Every corner must (initially) be provided a corner radius greater than

1 or else no corners are rounded If you want specific corners to not be rounded a work-around is to use androidradius to set a default corner

radius greater than 1 but then override each and every corner with the values you really want providing zero (0dp) where you dont want rounded

corners

ltgradientgt

Specifies a gradient color for the shape

Attributes

androidangle

Integer The angle for the gradient in degrees 0 is left to right 90 is bottom

to top It must be a multiple of 45 Default is 0

androidcenterX

Float The relative X-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterY

Float The relative Y-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterColor

Color Optional color that comes between the start and end colors as a

hexadecimal value or color resource

androidendColor

Color The ending color as a hexadecimal value or color resource

androidgradientRadius

Float The radius for the gradient Only applied when androidtype=radial

androidstartColor

Color The starting color as a hexadecimal value or color resource

androidtype

Keyword The type of gradient pattern to apply Valid values are

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 25

Value Description

linear A linear gradient This is the default

radial A radial gradient The start color is the center color

sweep A sweeping line gradient

androiduseLevel

Boolean true if this is used as a LevelListDrawable

ltpaddinggt

Padding to apply to the containing View element (this pads the position of

the View content not the shape)

Attributes

androidleft

Dimension Left padding as a dimension value or dimension resource

androidtop

Dimension Top padding as a dimension value or dimension resource

androidright

Dimension Right padding as a dimension value or dimension resource

androidbottom

Dimension Bottom padding as a dimension value or dimension resource

ltsizegt

The size of the shape

Attributes

androidheight

Dimension The height of the shape as a dimension value or dimension

resource

androidwidth

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 26

Dimension The width of the shape as a dimension value or dimension

resource

Note The shape scales to the size of the container View proportionate to the

dimensions defined here by default When you use the shape in an ImageView you can restrict scaling by setting the androidscaleType to center

ltsolidgt

A solid color to fill the shape

Attributes

androidcolor

Color The color to apply to the shape as a hexadecimal value or color

resource

ltstrokegt

A stroke line for the shape

Attributes

androidwidth

Dimension The thickness of the line as a dimension value or dimension

resource

androidcolor

Color The color of the line as a hexadecimal value or color resource

androiddashGap

Dimension The distance between line dashes as a dimension value or

dimension resource Only valid if androiddashWidth is set

androiddashWidth

Dimension The size of each dash line as a dimension value or dimension

resource Only valid if androiddashGap is set

Example

XML file saved at resdrawablegradient_boxxml

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 27

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=rectanglegt ltgradient androidstartColor=FFFF0000 androidendColor=80FF00FF androidangle=45gt ltpadding androidleft=7dp androidtop=7dp androidright=7dp androidbottom=7dp gt ltcorners androidradius=8dp gt ltshapegt

This layout XML applies the shape drawable to a View

ltTextView androidbackground=drawablegradient_box androidlayout_height=wrap_content androidlayout_width=wrap_content gt

This application code gets the shape drawable and applies it to a View

Resources res = getResources() Drawable shape = res getDrawable(Rdrawablegradient_box)

TextView tv = (TextView)findViewByID(Ridtextview) tvsetBackground(shape)

Page 19: Android graphics mca 5th

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 19

Loading Custom typeface from asset

Typeface mType = TypefacecreateFromAsset(getContext()getAssets()ldquofontschess1ttfrdquo) Example ViewFontjava

package compritesh

import androidcontentContext import androidgraphicsCanvas import androidgraphicsColor import androidgraphicsPaint import androidgraphicsTypeface import androidviewView public class ViewFont extends View Context c public ViewFont(Context context) super(context) c=context protected void onDraw(Canvas canvas) Typeface mType = TypefacecreateFromAsset( cgetAssets() fontsBaroqueScriptttf) Paint p =new Paint(PaintANTI_ALIAS_FLAG) psetTypeface(mType) psetTextSize(20) canvasdrawColor(ColorBLUE) canvasdrawText(Welcome to Android canvasgetWidth()4 canvasgetHeight()3 p)

SampleCustomFontjava package compritesh import androidappActivity import androidgraphicsTypeface import androidosBundle public class SampleCustomFont extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain) setContentView(new ViewFont(this))

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 20

Working with Bitmap and Matrix Bitmap

In computer graphics a bitmap or pixmap is a type of memory organization

or image file format used to store digital images The term bitmap comes from the

computer programming terminology meaning just a map of bits a spatially mapped array of bits Now along with pixmap it commonly refers to the similar

concept of a spatially mapped array of pixels Raster images in general may be referred to as bitmaps or pixmaps whether synthetic or photographic in files or

memory In certain contexts the term bitmap implies one bit per pixel while pixmap

is used for images with multiple bits per pixel

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 21

Shape Drawable in XML

This is a generic shape defined in XML

File location

resdrawablefilenamexml

The filename is used as the resource ID

Compiled resource datatype

Resource pointer to a GradientDrawable

Resource reference

In Java Rdrawablefilename

In XML [package]drawablefilename

Syntax

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=[rectangle | oval | line | ring] gt ltcorners androidradius=integer androidtopLeftRadius=integer androidtopRightRadius=integer androidbottomLeftRadius=integer androidbottomRightRadius=integer gt ltgradient androidangle=integer androidcenterX=integer androidcenterY=integer androidcenterColor=integer androidendColor=color androidgradientRadius=integer androidstartColor=color androidtype=[linear | radial | sweep] androidusesLevel=[true | false] gt ltpadding androidleft=integer androidtop=integer androidright=integer androidbottom=integer gt ltsize androidwidth=integer androidheight=integer gt ltsolid

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 22

androidcolor=color gt ltstroke androidwidth=integer androidcolor=color androiddashWidth=integer androiddashGap=integer gt ltshapegt

Elements

ltshapegt

The shape drawable This must be the root element

Attributes

xmlnsandroid

String Required Defines the XML namespace which must be

httpschemasandroidcomapkresandroid

androidshape

Keyword Defines the type of shape Valid values are

Value Desciption

rectangle A rectangle that fills the containing View This is the default shape

oval An oval shape that fits the dimensions of the containing View

line A horizontal line that spans the width of the containing View This

shape requires the ltstrokegt element to define the width of the line

ring A ring shape

The following attributes are used only when androidshape=ring

androidinnerRadius

Dimension The radius for the inner part of the ring (the hole in the middle)

as a dimension value or dimension resource

androidinnerRadiusRatio

Float The radius for the inner part of the ring expressed as a ratio of the

rings width For instance if androidinnerRadiusRatio=5 then the inner

radius equals the rings width divided by 5 This value is overridden by

androidinnerRadius Default value is 9

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 23

androidthickness

Dimension The thickness of the ring as a dimension value or dimension

resource

androidthicknessRatio

Float The thickness of the ring expressed as a ratio of the rings width For

instance if androidthicknessRatio=2 then the thickness equals the rings

width divided by 2 This value is overridden by androidinnerRadius Default

value is 3

androiduseLevel

Boolean true if this is used as a LevelListDrawable This should normally

be false or your shape may not appear

ltcornersgt

Creates rounded corners for the shape Applies only when the shape is a

rectangle

Attributes

androidradius

Dimension The radius for all corners as a dimension value or dimension

resource This is overridden for each corner by the following attributes

androidtopLeftRadius

Dimension The radius for the top-left corner as a dimension value or

dimension resource

androidtopRightRadius

Dimension The radius for the top-right corner as a dimension value or

dimension resource

androidbottomLeftRadius

Dimension The radius for the bottom-left corner as a dimension value or

dimension resource

androidbottomRightRadius

Dimension The radius for the bottom-right corner as a dimension value or

dimension resource

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 24

Note Every corner must (initially) be provided a corner radius greater than

1 or else no corners are rounded If you want specific corners to not be rounded a work-around is to use androidradius to set a default corner

radius greater than 1 but then override each and every corner with the values you really want providing zero (0dp) where you dont want rounded

corners

ltgradientgt

Specifies a gradient color for the shape

Attributes

androidangle

Integer The angle for the gradient in degrees 0 is left to right 90 is bottom

to top It must be a multiple of 45 Default is 0

androidcenterX

Float The relative X-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterY

Float The relative Y-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterColor

Color Optional color that comes between the start and end colors as a

hexadecimal value or color resource

androidendColor

Color The ending color as a hexadecimal value or color resource

androidgradientRadius

Float The radius for the gradient Only applied when androidtype=radial

androidstartColor

Color The starting color as a hexadecimal value or color resource

androidtype

Keyword The type of gradient pattern to apply Valid values are

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 25

Value Description

linear A linear gradient This is the default

radial A radial gradient The start color is the center color

sweep A sweeping line gradient

androiduseLevel

Boolean true if this is used as a LevelListDrawable

ltpaddinggt

Padding to apply to the containing View element (this pads the position of

the View content not the shape)

Attributes

androidleft

Dimension Left padding as a dimension value or dimension resource

androidtop

Dimension Top padding as a dimension value or dimension resource

androidright

Dimension Right padding as a dimension value or dimension resource

androidbottom

Dimension Bottom padding as a dimension value or dimension resource

ltsizegt

The size of the shape

Attributes

androidheight

Dimension The height of the shape as a dimension value or dimension

resource

androidwidth

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 26

Dimension The width of the shape as a dimension value or dimension

resource

Note The shape scales to the size of the container View proportionate to the

dimensions defined here by default When you use the shape in an ImageView you can restrict scaling by setting the androidscaleType to center

ltsolidgt

A solid color to fill the shape

Attributes

androidcolor

Color The color to apply to the shape as a hexadecimal value or color

resource

ltstrokegt

A stroke line for the shape

Attributes

androidwidth

Dimension The thickness of the line as a dimension value or dimension

resource

androidcolor

Color The color of the line as a hexadecimal value or color resource

androiddashGap

Dimension The distance between line dashes as a dimension value or

dimension resource Only valid if androiddashWidth is set

androiddashWidth

Dimension The size of each dash line as a dimension value or dimension

resource Only valid if androiddashGap is set

Example

XML file saved at resdrawablegradient_boxxml

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 27

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=rectanglegt ltgradient androidstartColor=FFFF0000 androidendColor=80FF00FF androidangle=45gt ltpadding androidleft=7dp androidtop=7dp androidright=7dp androidbottom=7dp gt ltcorners androidradius=8dp gt ltshapegt

This layout XML applies the shape drawable to a View

ltTextView androidbackground=drawablegradient_box androidlayout_height=wrap_content androidlayout_width=wrap_content gt

This application code gets the shape drawable and applies it to a View

Resources res = getResources() Drawable shape = res getDrawable(Rdrawablegradient_box)

TextView tv = (TextView)findViewByID(Ridtextview) tvsetBackground(shape)

Page 20: Android graphics mca 5th

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 20

Working with Bitmap and Matrix Bitmap

In computer graphics a bitmap or pixmap is a type of memory organization

or image file format used to store digital images The term bitmap comes from the

computer programming terminology meaning just a map of bits a spatially mapped array of bits Now along with pixmap it commonly refers to the similar

concept of a spatially mapped array of pixels Raster images in general may be referred to as bitmaps or pixmaps whether synthetic or photographic in files or

memory In certain contexts the term bitmap implies one bit per pixel while pixmap

is used for images with multiple bits per pixel

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 21

Shape Drawable in XML

This is a generic shape defined in XML

File location

resdrawablefilenamexml

The filename is used as the resource ID

Compiled resource datatype

Resource pointer to a GradientDrawable

Resource reference

In Java Rdrawablefilename

In XML [package]drawablefilename

Syntax

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=[rectangle | oval | line | ring] gt ltcorners androidradius=integer androidtopLeftRadius=integer androidtopRightRadius=integer androidbottomLeftRadius=integer androidbottomRightRadius=integer gt ltgradient androidangle=integer androidcenterX=integer androidcenterY=integer androidcenterColor=integer androidendColor=color androidgradientRadius=integer androidstartColor=color androidtype=[linear | radial | sweep] androidusesLevel=[true | false] gt ltpadding androidleft=integer androidtop=integer androidright=integer androidbottom=integer gt ltsize androidwidth=integer androidheight=integer gt ltsolid

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 22

androidcolor=color gt ltstroke androidwidth=integer androidcolor=color androiddashWidth=integer androiddashGap=integer gt ltshapegt

Elements

ltshapegt

The shape drawable This must be the root element

Attributes

xmlnsandroid

String Required Defines the XML namespace which must be

httpschemasandroidcomapkresandroid

androidshape

Keyword Defines the type of shape Valid values are

Value Desciption

rectangle A rectangle that fills the containing View This is the default shape

oval An oval shape that fits the dimensions of the containing View

line A horizontal line that spans the width of the containing View This

shape requires the ltstrokegt element to define the width of the line

ring A ring shape

The following attributes are used only when androidshape=ring

androidinnerRadius

Dimension The radius for the inner part of the ring (the hole in the middle)

as a dimension value or dimension resource

androidinnerRadiusRatio

Float The radius for the inner part of the ring expressed as a ratio of the

rings width For instance if androidinnerRadiusRatio=5 then the inner

radius equals the rings width divided by 5 This value is overridden by

androidinnerRadius Default value is 9

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 23

androidthickness

Dimension The thickness of the ring as a dimension value or dimension

resource

androidthicknessRatio

Float The thickness of the ring expressed as a ratio of the rings width For

instance if androidthicknessRatio=2 then the thickness equals the rings

width divided by 2 This value is overridden by androidinnerRadius Default

value is 3

androiduseLevel

Boolean true if this is used as a LevelListDrawable This should normally

be false or your shape may not appear

ltcornersgt

Creates rounded corners for the shape Applies only when the shape is a

rectangle

Attributes

androidradius

Dimension The radius for all corners as a dimension value or dimension

resource This is overridden for each corner by the following attributes

androidtopLeftRadius

Dimension The radius for the top-left corner as a dimension value or

dimension resource

androidtopRightRadius

Dimension The radius for the top-right corner as a dimension value or

dimension resource

androidbottomLeftRadius

Dimension The radius for the bottom-left corner as a dimension value or

dimension resource

androidbottomRightRadius

Dimension The radius for the bottom-right corner as a dimension value or

dimension resource

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 24

Note Every corner must (initially) be provided a corner radius greater than

1 or else no corners are rounded If you want specific corners to not be rounded a work-around is to use androidradius to set a default corner

radius greater than 1 but then override each and every corner with the values you really want providing zero (0dp) where you dont want rounded

corners

ltgradientgt

Specifies a gradient color for the shape

Attributes

androidangle

Integer The angle for the gradient in degrees 0 is left to right 90 is bottom

to top It must be a multiple of 45 Default is 0

androidcenterX

Float The relative X-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterY

Float The relative Y-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterColor

Color Optional color that comes between the start and end colors as a

hexadecimal value or color resource

androidendColor

Color The ending color as a hexadecimal value or color resource

androidgradientRadius

Float The radius for the gradient Only applied when androidtype=radial

androidstartColor

Color The starting color as a hexadecimal value or color resource

androidtype

Keyword The type of gradient pattern to apply Valid values are

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 25

Value Description

linear A linear gradient This is the default

radial A radial gradient The start color is the center color

sweep A sweeping line gradient

androiduseLevel

Boolean true if this is used as a LevelListDrawable

ltpaddinggt

Padding to apply to the containing View element (this pads the position of

the View content not the shape)

Attributes

androidleft

Dimension Left padding as a dimension value or dimension resource

androidtop

Dimension Top padding as a dimension value or dimension resource

androidright

Dimension Right padding as a dimension value or dimension resource

androidbottom

Dimension Bottom padding as a dimension value or dimension resource

ltsizegt

The size of the shape

Attributes

androidheight

Dimension The height of the shape as a dimension value or dimension

resource

androidwidth

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 26

Dimension The width of the shape as a dimension value or dimension

resource

Note The shape scales to the size of the container View proportionate to the

dimensions defined here by default When you use the shape in an ImageView you can restrict scaling by setting the androidscaleType to center

ltsolidgt

A solid color to fill the shape

Attributes

androidcolor

Color The color to apply to the shape as a hexadecimal value or color

resource

ltstrokegt

A stroke line for the shape

Attributes

androidwidth

Dimension The thickness of the line as a dimension value or dimension

resource

androidcolor

Color The color of the line as a hexadecimal value or color resource

androiddashGap

Dimension The distance between line dashes as a dimension value or

dimension resource Only valid if androiddashWidth is set

androiddashWidth

Dimension The size of each dash line as a dimension value or dimension

resource Only valid if androiddashGap is set

Example

XML file saved at resdrawablegradient_boxxml

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 27

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=rectanglegt ltgradient androidstartColor=FFFF0000 androidendColor=80FF00FF androidangle=45gt ltpadding androidleft=7dp androidtop=7dp androidright=7dp androidbottom=7dp gt ltcorners androidradius=8dp gt ltshapegt

This layout XML applies the shape drawable to a View

ltTextView androidbackground=drawablegradient_box androidlayout_height=wrap_content androidlayout_width=wrap_content gt

This application code gets the shape drawable and applies it to a View

Resources res = getResources() Drawable shape = res getDrawable(Rdrawablegradient_box)

TextView tv = (TextView)findViewByID(Ridtextview) tvsetBackground(shape)

Page 21: Android graphics mca 5th

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 21

Shape Drawable in XML

This is a generic shape defined in XML

File location

resdrawablefilenamexml

The filename is used as the resource ID

Compiled resource datatype

Resource pointer to a GradientDrawable

Resource reference

In Java Rdrawablefilename

In XML [package]drawablefilename

Syntax

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=[rectangle | oval | line | ring] gt ltcorners androidradius=integer androidtopLeftRadius=integer androidtopRightRadius=integer androidbottomLeftRadius=integer androidbottomRightRadius=integer gt ltgradient androidangle=integer androidcenterX=integer androidcenterY=integer androidcenterColor=integer androidendColor=color androidgradientRadius=integer androidstartColor=color androidtype=[linear | radial | sweep] androidusesLevel=[true | false] gt ltpadding androidleft=integer androidtop=integer androidright=integer androidbottom=integer gt ltsize androidwidth=integer androidheight=integer gt ltsolid

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 22

androidcolor=color gt ltstroke androidwidth=integer androidcolor=color androiddashWidth=integer androiddashGap=integer gt ltshapegt

Elements

ltshapegt

The shape drawable This must be the root element

Attributes

xmlnsandroid

String Required Defines the XML namespace which must be

httpschemasandroidcomapkresandroid

androidshape

Keyword Defines the type of shape Valid values are

Value Desciption

rectangle A rectangle that fills the containing View This is the default shape

oval An oval shape that fits the dimensions of the containing View

line A horizontal line that spans the width of the containing View This

shape requires the ltstrokegt element to define the width of the line

ring A ring shape

The following attributes are used only when androidshape=ring

androidinnerRadius

Dimension The radius for the inner part of the ring (the hole in the middle)

as a dimension value or dimension resource

androidinnerRadiusRatio

Float The radius for the inner part of the ring expressed as a ratio of the

rings width For instance if androidinnerRadiusRatio=5 then the inner

radius equals the rings width divided by 5 This value is overridden by

androidinnerRadius Default value is 9

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 23

androidthickness

Dimension The thickness of the ring as a dimension value or dimension

resource

androidthicknessRatio

Float The thickness of the ring expressed as a ratio of the rings width For

instance if androidthicknessRatio=2 then the thickness equals the rings

width divided by 2 This value is overridden by androidinnerRadius Default

value is 3

androiduseLevel

Boolean true if this is used as a LevelListDrawable This should normally

be false or your shape may not appear

ltcornersgt

Creates rounded corners for the shape Applies only when the shape is a

rectangle

Attributes

androidradius

Dimension The radius for all corners as a dimension value or dimension

resource This is overridden for each corner by the following attributes

androidtopLeftRadius

Dimension The radius for the top-left corner as a dimension value or

dimension resource

androidtopRightRadius

Dimension The radius for the top-right corner as a dimension value or

dimension resource

androidbottomLeftRadius

Dimension The radius for the bottom-left corner as a dimension value or

dimension resource

androidbottomRightRadius

Dimension The radius for the bottom-right corner as a dimension value or

dimension resource

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 24

Note Every corner must (initially) be provided a corner radius greater than

1 or else no corners are rounded If you want specific corners to not be rounded a work-around is to use androidradius to set a default corner

radius greater than 1 but then override each and every corner with the values you really want providing zero (0dp) where you dont want rounded

corners

ltgradientgt

Specifies a gradient color for the shape

Attributes

androidangle

Integer The angle for the gradient in degrees 0 is left to right 90 is bottom

to top It must be a multiple of 45 Default is 0

androidcenterX

Float The relative X-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterY

Float The relative Y-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterColor

Color Optional color that comes between the start and end colors as a

hexadecimal value or color resource

androidendColor

Color The ending color as a hexadecimal value or color resource

androidgradientRadius

Float The radius for the gradient Only applied when androidtype=radial

androidstartColor

Color The starting color as a hexadecimal value or color resource

androidtype

Keyword The type of gradient pattern to apply Valid values are

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 25

Value Description

linear A linear gradient This is the default

radial A radial gradient The start color is the center color

sweep A sweeping line gradient

androiduseLevel

Boolean true if this is used as a LevelListDrawable

ltpaddinggt

Padding to apply to the containing View element (this pads the position of

the View content not the shape)

Attributes

androidleft

Dimension Left padding as a dimension value or dimension resource

androidtop

Dimension Top padding as a dimension value or dimension resource

androidright

Dimension Right padding as a dimension value or dimension resource

androidbottom

Dimension Bottom padding as a dimension value or dimension resource

ltsizegt

The size of the shape

Attributes

androidheight

Dimension The height of the shape as a dimension value or dimension

resource

androidwidth

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 26

Dimension The width of the shape as a dimension value or dimension

resource

Note The shape scales to the size of the container View proportionate to the

dimensions defined here by default When you use the shape in an ImageView you can restrict scaling by setting the androidscaleType to center

ltsolidgt

A solid color to fill the shape

Attributes

androidcolor

Color The color to apply to the shape as a hexadecimal value or color

resource

ltstrokegt

A stroke line for the shape

Attributes

androidwidth

Dimension The thickness of the line as a dimension value or dimension

resource

androidcolor

Color The color of the line as a hexadecimal value or color resource

androiddashGap

Dimension The distance between line dashes as a dimension value or

dimension resource Only valid if androiddashWidth is set

androiddashWidth

Dimension The size of each dash line as a dimension value or dimension

resource Only valid if androiddashGap is set

Example

XML file saved at resdrawablegradient_boxxml

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 27

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=rectanglegt ltgradient androidstartColor=FFFF0000 androidendColor=80FF00FF androidangle=45gt ltpadding androidleft=7dp androidtop=7dp androidright=7dp androidbottom=7dp gt ltcorners androidradius=8dp gt ltshapegt

This layout XML applies the shape drawable to a View

ltTextView androidbackground=drawablegradient_box androidlayout_height=wrap_content androidlayout_width=wrap_content gt

This application code gets the shape drawable and applies it to a View

Resources res = getResources() Drawable shape = res getDrawable(Rdrawablegradient_box)

TextView tv = (TextView)findViewByID(Ridtextview) tvsetBackground(shape)

Page 22: Android graphics mca 5th

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 22

androidcolor=color gt ltstroke androidwidth=integer androidcolor=color androiddashWidth=integer androiddashGap=integer gt ltshapegt

Elements

ltshapegt

The shape drawable This must be the root element

Attributes

xmlnsandroid

String Required Defines the XML namespace which must be

httpschemasandroidcomapkresandroid

androidshape

Keyword Defines the type of shape Valid values are

Value Desciption

rectangle A rectangle that fills the containing View This is the default shape

oval An oval shape that fits the dimensions of the containing View

line A horizontal line that spans the width of the containing View This

shape requires the ltstrokegt element to define the width of the line

ring A ring shape

The following attributes are used only when androidshape=ring

androidinnerRadius

Dimension The radius for the inner part of the ring (the hole in the middle)

as a dimension value or dimension resource

androidinnerRadiusRatio

Float The radius for the inner part of the ring expressed as a ratio of the

rings width For instance if androidinnerRadiusRatio=5 then the inner

radius equals the rings width divided by 5 This value is overridden by

androidinnerRadius Default value is 9

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 23

androidthickness

Dimension The thickness of the ring as a dimension value or dimension

resource

androidthicknessRatio

Float The thickness of the ring expressed as a ratio of the rings width For

instance if androidthicknessRatio=2 then the thickness equals the rings

width divided by 2 This value is overridden by androidinnerRadius Default

value is 3

androiduseLevel

Boolean true if this is used as a LevelListDrawable This should normally

be false or your shape may not appear

ltcornersgt

Creates rounded corners for the shape Applies only when the shape is a

rectangle

Attributes

androidradius

Dimension The radius for all corners as a dimension value or dimension

resource This is overridden for each corner by the following attributes

androidtopLeftRadius

Dimension The radius for the top-left corner as a dimension value or

dimension resource

androidtopRightRadius

Dimension The radius for the top-right corner as a dimension value or

dimension resource

androidbottomLeftRadius

Dimension The radius for the bottom-left corner as a dimension value or

dimension resource

androidbottomRightRadius

Dimension The radius for the bottom-right corner as a dimension value or

dimension resource

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 24

Note Every corner must (initially) be provided a corner radius greater than

1 or else no corners are rounded If you want specific corners to not be rounded a work-around is to use androidradius to set a default corner

radius greater than 1 but then override each and every corner with the values you really want providing zero (0dp) where you dont want rounded

corners

ltgradientgt

Specifies a gradient color for the shape

Attributes

androidangle

Integer The angle for the gradient in degrees 0 is left to right 90 is bottom

to top It must be a multiple of 45 Default is 0

androidcenterX

Float The relative X-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterY

Float The relative Y-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterColor

Color Optional color that comes between the start and end colors as a

hexadecimal value or color resource

androidendColor

Color The ending color as a hexadecimal value or color resource

androidgradientRadius

Float The radius for the gradient Only applied when androidtype=radial

androidstartColor

Color The starting color as a hexadecimal value or color resource

androidtype

Keyword The type of gradient pattern to apply Valid values are

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 25

Value Description

linear A linear gradient This is the default

radial A radial gradient The start color is the center color

sweep A sweeping line gradient

androiduseLevel

Boolean true if this is used as a LevelListDrawable

ltpaddinggt

Padding to apply to the containing View element (this pads the position of

the View content not the shape)

Attributes

androidleft

Dimension Left padding as a dimension value or dimension resource

androidtop

Dimension Top padding as a dimension value or dimension resource

androidright

Dimension Right padding as a dimension value or dimension resource

androidbottom

Dimension Bottom padding as a dimension value or dimension resource

ltsizegt

The size of the shape

Attributes

androidheight

Dimension The height of the shape as a dimension value or dimension

resource

androidwidth

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 26

Dimension The width of the shape as a dimension value or dimension

resource

Note The shape scales to the size of the container View proportionate to the

dimensions defined here by default When you use the shape in an ImageView you can restrict scaling by setting the androidscaleType to center

ltsolidgt

A solid color to fill the shape

Attributes

androidcolor

Color The color to apply to the shape as a hexadecimal value or color

resource

ltstrokegt

A stroke line for the shape

Attributes

androidwidth

Dimension The thickness of the line as a dimension value or dimension

resource

androidcolor

Color The color of the line as a hexadecimal value or color resource

androiddashGap

Dimension The distance between line dashes as a dimension value or

dimension resource Only valid if androiddashWidth is set

androiddashWidth

Dimension The size of each dash line as a dimension value or dimension

resource Only valid if androiddashGap is set

Example

XML file saved at resdrawablegradient_boxxml

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 27

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=rectanglegt ltgradient androidstartColor=FFFF0000 androidendColor=80FF00FF androidangle=45gt ltpadding androidleft=7dp androidtop=7dp androidright=7dp androidbottom=7dp gt ltcorners androidradius=8dp gt ltshapegt

This layout XML applies the shape drawable to a View

ltTextView androidbackground=drawablegradient_box androidlayout_height=wrap_content androidlayout_width=wrap_content gt

This application code gets the shape drawable and applies it to a View

Resources res = getResources() Drawable shape = res getDrawable(Rdrawablegradient_box)

TextView tv = (TextView)findViewByID(Ridtextview) tvsetBackground(shape)

Page 23: Android graphics mca 5th

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 23

androidthickness

Dimension The thickness of the ring as a dimension value or dimension

resource

androidthicknessRatio

Float The thickness of the ring expressed as a ratio of the rings width For

instance if androidthicknessRatio=2 then the thickness equals the rings

width divided by 2 This value is overridden by androidinnerRadius Default

value is 3

androiduseLevel

Boolean true if this is used as a LevelListDrawable This should normally

be false or your shape may not appear

ltcornersgt

Creates rounded corners for the shape Applies only when the shape is a

rectangle

Attributes

androidradius

Dimension The radius for all corners as a dimension value or dimension

resource This is overridden for each corner by the following attributes

androidtopLeftRadius

Dimension The radius for the top-left corner as a dimension value or

dimension resource

androidtopRightRadius

Dimension The radius for the top-right corner as a dimension value or

dimension resource

androidbottomLeftRadius

Dimension The radius for the bottom-left corner as a dimension value or

dimension resource

androidbottomRightRadius

Dimension The radius for the bottom-right corner as a dimension value or

dimension resource

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 24

Note Every corner must (initially) be provided a corner radius greater than

1 or else no corners are rounded If you want specific corners to not be rounded a work-around is to use androidradius to set a default corner

radius greater than 1 but then override each and every corner with the values you really want providing zero (0dp) where you dont want rounded

corners

ltgradientgt

Specifies a gradient color for the shape

Attributes

androidangle

Integer The angle for the gradient in degrees 0 is left to right 90 is bottom

to top It must be a multiple of 45 Default is 0

androidcenterX

Float The relative X-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterY

Float The relative Y-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterColor

Color Optional color that comes between the start and end colors as a

hexadecimal value or color resource

androidendColor

Color The ending color as a hexadecimal value or color resource

androidgradientRadius

Float The radius for the gradient Only applied when androidtype=radial

androidstartColor

Color The starting color as a hexadecimal value or color resource

androidtype

Keyword The type of gradient pattern to apply Valid values are

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 25

Value Description

linear A linear gradient This is the default

radial A radial gradient The start color is the center color

sweep A sweeping line gradient

androiduseLevel

Boolean true if this is used as a LevelListDrawable

ltpaddinggt

Padding to apply to the containing View element (this pads the position of

the View content not the shape)

Attributes

androidleft

Dimension Left padding as a dimension value or dimension resource

androidtop

Dimension Top padding as a dimension value or dimension resource

androidright

Dimension Right padding as a dimension value or dimension resource

androidbottom

Dimension Bottom padding as a dimension value or dimension resource

ltsizegt

The size of the shape

Attributes

androidheight

Dimension The height of the shape as a dimension value or dimension

resource

androidwidth

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 26

Dimension The width of the shape as a dimension value or dimension

resource

Note The shape scales to the size of the container View proportionate to the

dimensions defined here by default When you use the shape in an ImageView you can restrict scaling by setting the androidscaleType to center

ltsolidgt

A solid color to fill the shape

Attributes

androidcolor

Color The color to apply to the shape as a hexadecimal value or color

resource

ltstrokegt

A stroke line for the shape

Attributes

androidwidth

Dimension The thickness of the line as a dimension value or dimension

resource

androidcolor

Color The color of the line as a hexadecimal value or color resource

androiddashGap

Dimension The distance between line dashes as a dimension value or

dimension resource Only valid if androiddashWidth is set

androiddashWidth

Dimension The size of each dash line as a dimension value or dimension

resource Only valid if androiddashGap is set

Example

XML file saved at resdrawablegradient_boxxml

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 27

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=rectanglegt ltgradient androidstartColor=FFFF0000 androidendColor=80FF00FF androidangle=45gt ltpadding androidleft=7dp androidtop=7dp androidright=7dp androidbottom=7dp gt ltcorners androidradius=8dp gt ltshapegt

This layout XML applies the shape drawable to a View

ltTextView androidbackground=drawablegradient_box androidlayout_height=wrap_content androidlayout_width=wrap_content gt

This application code gets the shape drawable and applies it to a View

Resources res = getResources() Drawable shape = res getDrawable(Rdrawablegradient_box)

TextView tv = (TextView)findViewByID(Ridtextview) tvsetBackground(shape)

Page 24: Android graphics mca 5th

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 24

Note Every corner must (initially) be provided a corner radius greater than

1 or else no corners are rounded If you want specific corners to not be rounded a work-around is to use androidradius to set a default corner

radius greater than 1 but then override each and every corner with the values you really want providing zero (0dp) where you dont want rounded

corners

ltgradientgt

Specifies a gradient color for the shape

Attributes

androidangle

Integer The angle for the gradient in degrees 0 is left to right 90 is bottom

to top It must be a multiple of 45 Default is 0

androidcenterX

Float The relative X-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterY

Float The relative Y-position for the center of the gradient (0 - 10) Does not

apply when androidtype=linear

androidcenterColor

Color Optional color that comes between the start and end colors as a

hexadecimal value or color resource

androidendColor

Color The ending color as a hexadecimal value or color resource

androidgradientRadius

Float The radius for the gradient Only applied when androidtype=radial

androidstartColor

Color The starting color as a hexadecimal value or color resource

androidtype

Keyword The type of gradient pattern to apply Valid values are

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 25

Value Description

linear A linear gradient This is the default

radial A radial gradient The start color is the center color

sweep A sweeping line gradient

androiduseLevel

Boolean true if this is used as a LevelListDrawable

ltpaddinggt

Padding to apply to the containing View element (this pads the position of

the View content not the shape)

Attributes

androidleft

Dimension Left padding as a dimension value or dimension resource

androidtop

Dimension Top padding as a dimension value or dimension resource

androidright

Dimension Right padding as a dimension value or dimension resource

androidbottom

Dimension Bottom padding as a dimension value or dimension resource

ltsizegt

The size of the shape

Attributes

androidheight

Dimension The height of the shape as a dimension value or dimension

resource

androidwidth

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 26

Dimension The width of the shape as a dimension value or dimension

resource

Note The shape scales to the size of the container View proportionate to the

dimensions defined here by default When you use the shape in an ImageView you can restrict scaling by setting the androidscaleType to center

ltsolidgt

A solid color to fill the shape

Attributes

androidcolor

Color The color to apply to the shape as a hexadecimal value or color

resource

ltstrokegt

A stroke line for the shape

Attributes

androidwidth

Dimension The thickness of the line as a dimension value or dimension

resource

androidcolor

Color The color of the line as a hexadecimal value or color resource

androiddashGap

Dimension The distance between line dashes as a dimension value or

dimension resource Only valid if androiddashWidth is set

androiddashWidth

Dimension The size of each dash line as a dimension value or dimension

resource Only valid if androiddashGap is set

Example

XML file saved at resdrawablegradient_boxxml

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 27

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=rectanglegt ltgradient androidstartColor=FFFF0000 androidendColor=80FF00FF androidangle=45gt ltpadding androidleft=7dp androidtop=7dp androidright=7dp androidbottom=7dp gt ltcorners androidradius=8dp gt ltshapegt

This layout XML applies the shape drawable to a View

ltTextView androidbackground=drawablegradient_box androidlayout_height=wrap_content androidlayout_width=wrap_content gt

This application code gets the shape drawable and applies it to a View

Resources res = getResources() Drawable shape = res getDrawable(Rdrawablegradient_box)

TextView tv = (TextView)findViewByID(Ridtextview) tvsetBackground(shape)

Page 25: Android graphics mca 5th

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 25

Value Description

linear A linear gradient This is the default

radial A radial gradient The start color is the center color

sweep A sweeping line gradient

androiduseLevel

Boolean true if this is used as a LevelListDrawable

ltpaddinggt

Padding to apply to the containing View element (this pads the position of

the View content not the shape)

Attributes

androidleft

Dimension Left padding as a dimension value or dimension resource

androidtop

Dimension Top padding as a dimension value or dimension resource

androidright

Dimension Right padding as a dimension value or dimension resource

androidbottom

Dimension Bottom padding as a dimension value or dimension resource

ltsizegt

The size of the shape

Attributes

androidheight

Dimension The height of the shape as a dimension value or dimension

resource

androidwidth

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 26

Dimension The width of the shape as a dimension value or dimension

resource

Note The shape scales to the size of the container View proportionate to the

dimensions defined here by default When you use the shape in an ImageView you can restrict scaling by setting the androidscaleType to center

ltsolidgt

A solid color to fill the shape

Attributes

androidcolor

Color The color to apply to the shape as a hexadecimal value or color

resource

ltstrokegt

A stroke line for the shape

Attributes

androidwidth

Dimension The thickness of the line as a dimension value or dimension

resource

androidcolor

Color The color of the line as a hexadecimal value or color resource

androiddashGap

Dimension The distance between line dashes as a dimension value or

dimension resource Only valid if androiddashWidth is set

androiddashWidth

Dimension The size of each dash line as a dimension value or dimension

resource Only valid if androiddashGap is set

Example

XML file saved at resdrawablegradient_boxxml

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 27

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=rectanglegt ltgradient androidstartColor=FFFF0000 androidendColor=80FF00FF androidangle=45gt ltpadding androidleft=7dp androidtop=7dp androidright=7dp androidbottom=7dp gt ltcorners androidradius=8dp gt ltshapegt

This layout XML applies the shape drawable to a View

ltTextView androidbackground=drawablegradient_box androidlayout_height=wrap_content androidlayout_width=wrap_content gt

This application code gets the shape drawable and applies it to a View

Resources res = getResources() Drawable shape = res getDrawable(Rdrawablegradient_box)

TextView tv = (TextView)findViewByID(Ridtextview) tvsetBackground(shape)

Page 26: Android graphics mca 5th

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 26

Dimension The width of the shape as a dimension value or dimension

resource

Note The shape scales to the size of the container View proportionate to the

dimensions defined here by default When you use the shape in an ImageView you can restrict scaling by setting the androidscaleType to center

ltsolidgt

A solid color to fill the shape

Attributes

androidcolor

Color The color to apply to the shape as a hexadecimal value or color

resource

ltstrokegt

A stroke line for the shape

Attributes

androidwidth

Dimension The thickness of the line as a dimension value or dimension

resource

androidcolor

Color The color of the line as a hexadecimal value or color resource

androiddashGap

Dimension The distance between line dashes as a dimension value or

dimension resource Only valid if androiddashWidth is set

androiddashWidth

Dimension The size of each dash line as a dimension value or dimension

resource Only valid if androiddashGap is set

Example

XML file saved at resdrawablegradient_boxxml

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 27

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=rectanglegt ltgradient androidstartColor=FFFF0000 androidendColor=80FF00FF androidangle=45gt ltpadding androidleft=7dp androidtop=7dp androidright=7dp androidbottom=7dp gt ltcorners androidradius=8dp gt ltshapegt

This layout XML applies the shape drawable to a View

ltTextView androidbackground=drawablegradient_box androidlayout_height=wrap_content androidlayout_width=wrap_content gt

This application code gets the shape drawable and applies it to a View

Resources res = getResources() Drawable shape = res getDrawable(Rdrawablegradient_box)

TextView tv = (TextView)findViewByID(Ridtextview) tvsetBackground(shape)

Page 27: Android graphics mca 5th

Android Graphics ndash MCA 5th 650003

Mr Pritesh N Patel ISTAR Page 27

ltxml version=10 encoding=utf-8gt ltshape xmlnsandroid=httpschemasandroidcomapkresandroid androidshape=rectanglegt ltgradient androidstartColor=FFFF0000 androidendColor=80FF00FF androidangle=45gt ltpadding androidleft=7dp androidtop=7dp androidright=7dp androidbottom=7dp gt ltcorners androidradius=8dp gt ltshapegt

This layout XML applies the shape drawable to a View

ltTextView androidbackground=drawablegradient_box androidlayout_height=wrap_content androidlayout_width=wrap_content gt

This application code gets the shape drawable and applies it to a View

Resources res = getResources() Drawable shape = res getDrawable(Rdrawablegradient_box)

TextView tv = (TextView)findViewByID(Ridtextview) tvsetBackground(shape)