• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Android graphics mca 5th
 

Android graphics mca 5th

on

  • 347 views

 

Statistics

Views

Total Views
347
Views on SlideShare
347
Embed Views
0

Actions

Likes
0
Downloads
15
Comments
0

0 Embeds 0

No embeds

Accessibility

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Android graphics mca 5th Android graphics mca 5th Document Transcript

    • 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 650003 Mr. Pritesh N. Patel ISTAR Page 2  Draw with a Canvas When you're writing an application in which you would like to perform specialized drawing and/or 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 — 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 you're 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 SurfaceHolder.lockCanvas(), 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 = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_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 Canvas.drawBitmap(Bitmap,...) methods. It's recommended that you ultimately draw your final graphics through a Canvas offered to you by View.onDraw() or SurfaceHolder.lockCanvas() (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, you'll 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 View.onDraw(). 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 – 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 you'd 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 component's onDraw(), use the Canvas given to you for all your drawing, using various Canvas.draw...() 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 Activity's 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 application's secondary thread, so that the application isn't required to wait until the system's 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 SurfaceHolder.Callback. 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 you'd like to receive SurfaceHolder callbacks (from SurfaceHolder.Callback) by calling addCallback() (pass it this). Then override each of the SurfaceHolder.Callback 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 you're done drawing with the Canvas, call unlockCanvasAndPost(), passing it your Canvas object. The Surface will now draw
    • Android Graphics – 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. Theandroid.graphics.drawable andandroid.view.animation packages are where you'll find the common classes used for drawing and animating in two- dimensions. This document offers an introduction to drawing graphics in your Android application. We'll 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." You'll discover that the Drawable class extends to define a variety of specific kinds of drawable graphics, including BitmapDrawable, ShapeDrawable, PictureDrawable,LayerDrawable, 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, we'll 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 – MCA 5th 650003 Mr. Pritesh N. Patel ISTAR Page 5 To use an image resource, just add your file to the res/drawable/ 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 (E.g., my_image.png 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) { super.onCreate(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); i.setImageResource(R.drawable.my_image); i.setAdjustViewBounds(true); // set the ImageView bounds to match the Drawable's dimensions i.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); // Add the ImageView to the layout and set the layout as the content view mLinearLayout.addView(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 = mContext.getResources(); Drawable myImage = res.getDrawable(R.drawable.my_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). <ImageView android:layout_width="wrap_content"
    • Android Graphics – MCA 5th 650003 Mr. Pritesh N. Patel ISTAR Page 6 android:layout_height="wrap_content" android:tint="#55ff0000" android:src="@drawable/my_image"/> Creating from resource XML By now, you should be familiar with Android's 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 you'd 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 user's experience with your application, you should consider defining the object in XML, as you can always modify properties once it is instantiated. Once you've defined your Drawable in XML, save the file in the res/drawable/ directory of your project. Then, retrieve and instantiate the object by calling Resources.getDrawable(), 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 Here's some XML that defines a TransitionDrawable: <transition xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/image_expand"> <item android:drawable="@drawable/image_collapse"> </transition> With this XML saved in the file res/drawable/expand_collapse.xml, the following code will instantiate the TransitionDrawable and set it as the content of an ImageView: Resources res = mContext.getResources(); TransitionDrawable transition = (TransitionDrawable) res.getDrawable(R.drawable.expand_collapse);
    • Android Graphics – MCA 5th 650003 Mr. Pritesh N. Patel ISTAR Page 7 ImageView image = (ImageView) findViewById(R.id.toggle_image); image.setImageDrawable(transition); Then this transition can be run forward (for 1 second) with: transition.startTransition(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 (e.g. 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 top/left corner at (x,y), 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 x,y coordinates, using the specified paint. void drawLines(float[] pts, Paint paint)
    • Android Graphics – 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 character's origin specified by the pos array. void drawPosText(String text, float[] pos, Paint paint) Draw the text in the array, with each character's 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 (x,y), using the specified paint.
    • Android Graphics – 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 start/end, with its origin at (x,y), in the specified Paint. void drawText(char[] text, int index, int count, float x, float y, Paint paint) Draw the text, with origin at (x,y), using the specified paint. void drawText(String text, int start, int end, float x, float y, Paint paint) Draw the text, with origin at (x,y), using the specified paint. void drawTextOnPath(String text, Path path, float hOffset, float vOffset, Paint paint) Draw the text, with origin at (x,y), 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 (x,y), 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 – 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 Paint.Style FILL Geometry and text drawn with this style will be filled, ignoring all stroke-related settings in the paint. public static final Paint.Style 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 Paint.Style 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 color's alpha value. int getColor() Return the paint's color. ColorFilter getColorFilter() Get the paint's colorfilter (maybe be null). boolean getFillPath(Path src, Path dst) Applies any/all effects (patheffect, stroking) to src, returning the result in dst. int getFlags() Return the paint's flags.
    • Android Graphics – MCA 5th 650003 Mr. Pritesh N. Patel ISTAR Page 11 Paint.FontMetrics getFontMetrics() Allocates a new FontMetrics object, and then calls getFontMetrics(fm) with it, returning the object. int getFontMetricsInt(Paint.FontMetricsInt fmi) Return the font's interline spacing, given the Paint's settings for typeface, textSize, etc. float getFontSpacing() Return the recommend line spacing based on the current typeface and text size. MaskFilter getMaskFilter() Get the paint's maskfilter object. Shader getShader() Get the paint's shader object. Paint.Style getStyle() Return the paint's style, used for controlling how primitives' geometries are interpreted (except for drawBitmap, which always assumes FILL_STYLE). Paint.Align getTextAlign() Return the paint's 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 (0,0). 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 (0,0). 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 paint's horizontal scale factor for text. float getTextSize() Return the paint's text size. int getTextWidths(String text, float[] widths) Return the advance widths for the characters in the string.
    • Android Graphics – 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 paint's 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 a,r,g,b and constructs the color int void setAlpha(int a)
    • Android Graphics – MCA 5th 650003 Mr. Pritesh N. Patel ISTAR Page 13 Helper to setColor(), that only assigns the color's alpha value, leaving its r,g,b 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 paint's color. ColorFilter setColorFilter(ColorFilter filter) Set or clear the paint's 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 paint's 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(Paint.Style style) Set the paint's 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(Paint.Align align) Set the paint's text alignment. void setTextSize(float textSize) Set the paint's text size. void setTextSkewX(float skewX) Set the paint's horizontal skew factor for text.
    • Android Graphics – 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, Shader.TileMode 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 [0..1] 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 1.0. If the values are not monotonic, the drawing may produce unexpected results. If positions is
    • Android Graphics – 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, Shader.TileMode 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 paint.setShader(shader). After that any object (other than a bitmap) that is drawn with that paint will get its color(s) from the shader.  Shader.TileMode .CLAMP replicate the edge color if the shader draws outside of its original bounds  Shader.TileMode .MIRROR repeat the shader's image horizontally and vertically, alternating mirror images so that adjacent images always seam  Shader.TileMode .REPEAT repeat the shader's 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 << 24) | (red << 16) | (green << 8) | blue. Each component ranges between 0..255 with 0 meaning no contribution for that component, and 255
    • Android Graphics – 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 – 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 – 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 typeface's 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 android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Typeface; ... Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); Typeface mType; mPaint.setTextSize(16); mPaint.setTypeface(null); canvas.drawText(“Default Typeface”, 20, 20, mPaint); You can instead load a different typeface, such as Monotype: Typeface mType = Typeface.create(Typeface.MONOSPACE, Typeface.NORMAL); Perhaps you would prefer italic text, in which case you can simply set the style of the typeface and the font family: Typeface mType = Typeface.create(Typeface.SERIF, Typeface.ITALIC); You can set certain properties of a typeface such as antialiasing, underlining, and strikethrough using the setFlags() method of the Paint object: mPaint.setFlags(Paint.UNDERLINE_TEXT_FLAG);
    • Android Graphics – MCA 5th 650003 Mr. Pritesh N. Patel ISTAR Page 19 Loading Custom typeface from asset Typeface mType = Typeface.createFromAsset(getContext().getAssets(),“fonts/chess1.ttf”); Example ViewFont.java package com.pritesh; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Typeface; import android.view.View; public class ViewFont extends View { Context c; public ViewFont(Context context) { super(context); c=context; } protected void onDraw(Canvas canvas) { Typeface mType = Typeface.createFromAsset( c.getAssets(), "fonts/BaroqueScript.ttf"); Paint p =new Paint(Paint.ANTI_ALIAS_FLAG); p.setTypeface(mType); p.setTextSize(20); canvas.drawColor(Color.BLUE); canvas.drawText("Welcome to Android", canvas.getWidth()/4, canvas.getHeight()/3, p); } } SampleCustomFont.java package com.pritesh; import android.app.Activity; import android.graphics.Typeface; import android.os.Bundle; public class SampleCustomFont extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // setContentView(R.layout.main); setContentView(new ViewFont(this)); } }
    • Android Graphics – 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 – MCA 5th 650003 Mr. Pritesh N. Patel ISTAR Page 21 Shape Drawable in XML This is a generic shape defined in XML. File location: res/drawable/filename.xml The filename is used as the resource ID. Compiled resource datatype: Resource pointer to a GradientDrawable. Resource reference: In Java: R.drawable.filename In XML: @[package:]drawable/filename Syntax: <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape=["rectangle" | "oval" | "line" | "ring"] > <corners android:radius="integer" android:topLeftRadius="integer" android:topRightRadius="integer" android:bottomLeftRadius="integer" android:bottomRightRadius="integer" /> <gradient android:angle="integer" android:centerX="integer" android:centerY="integer" android:centerColor="integer" android:endColor="color" android:gradientRadius="integer" android:startColor="color" android:type=["linear" | "radial" | "sweep"] android:usesLevel=["true" | "false"] /> <padding android:left="integer" android:top="integer" android:right="integer" android:bottom="integer" /> <size android:width="integer" android:height="integer" /> <solid
    • Android Graphics – MCA 5th 650003 Mr. Pritesh N. Patel ISTAR Page 22 android:color="color" /> <stroke android:width="integer" android:color="color" android:dashWidth="integer" android:dashGap="integer" /> </shape> Elements: <shape> The shape drawable. This must be the root element. Attributes: xmlns:android String. Required. Defines the XML namespace, which must be "http://schemas.android.com/apk/res/android". android:shape 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 <stroke> element to define the width of the line. "ring" A ring shape. The following attributes are used only when android:shape="ring": android:innerRadius Dimension. The radius for the inner part of the ring (the hole in the middle), as a dimension value or dimension resource. android:innerRadiusRatio Float. The radius for the inner part of the ring, expressed as a ratio of the ring's width. For instance, if android:innerRadiusRatio="5", then the inner radius equals the ring's width divided by 5. This value is overridden by android:innerRadius. Default value is 9.
    • Android Graphics – MCA 5th 650003 Mr. Pritesh N. Patel ISTAR Page 23 android:thickness Dimension. The thickness of the ring, as a dimension value or dimension resource. android:thicknessRatio Float. The thickness of the ring, expressed as a ratio of the ring's width. For instance, if android:thicknessRatio="2", then the thickness equals the ring's width divided by 2. This value is overridden by android:innerRadius. Default value is 3. android:useLevel Boolean. "true" if this is used as a LevelListDrawable. This should normally be "false" or your shape may not appear. <corners> Creates rounded corners for the shape. Applies only when the shape is a rectangle. Attributes: android:radius Dimension. The radius for all corners, as a dimension value or dimension resource. This is overridden for each corner by the following attributes. android:topLeftRadius Dimension. The radius for the top-left corner, as a dimension value or dimension resource. android:topRightRadius Dimension. The radius for the top-right corner, as a dimension value or dimension resource. android:bottomLeftRadius Dimension. The radius for the bottom-left corner, as a dimension value or dimension resource. android:bottomRightRadius Dimension. The radius for the bottom-right corner, as a dimension value or dimension resource.
    • Android Graphics – 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 android:radius 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 don't want rounded corners. <gradient> Specifies a gradient color for the shape. Attributes: android:angle 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. android:centerX Float. The relative X-position for the center of the gradient (0 - 1.0). Does not apply when android:type="linear". android:centerY Float. The relative Y-position for the center of the gradient (0 - 1.0). Does not apply when android:type="linear". android:centerColor Color. Optional color that comes between the start and end colors, as a hexadecimal value or color resource. android:endColor Color. The ending color, as a hexadecimal value or color resource. android:gradientRadius Float. The radius for the gradient. Only applied when android:type="radial". android:startColor Color. The starting color, as a hexadecimal value or color resource. android:type Keyword. The type of gradient pattern to apply. Valid values are:
    • Android Graphics – 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. android:useLevel Boolean. "true" if this is used as a LevelListDrawable. <padding> Padding to apply to the containing View element (this pads the position of the View content, not the shape). Attributes: android:left Dimension. Left padding, as a dimension value or dimension resource. android:top Dimension. Top padding, as a dimension value or dimension resource. android:right Dimension. Right padding, as a dimension value or dimension resource. android:bottom Dimension. Bottom padding, as a dimension value or dimension resource. <size> The size of the shape. Attributes: android:height Dimension. The height of the shape, as a dimension value or dimension resource. android:width
    • Android Graphics – 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 android:scaleType to "center". <solid> A solid color to fill the shape. Attributes: android:color Color. The color to apply to the shape, as a hexadecimal value or color resource. <stroke> A stroke line for the shape. Attributes: android:width Dimension. The thickness of the line, as a dimension value or dimension resource. android:color Color. The color of the line, as a hexadecimal value or color resource. android:dashGap Dimension. The distance between line dashes, as a dimension value or dimension resource. Only valid if android:dashWidth is set. android:dashWidth Dimension. The size of each dash line, as a dimension value or dimension resource. Only valid if android:dashGap is set. Example: XML file saved at res/drawable/gradient_box.xml:
    • Android Graphics – MCA 5th 650003 Mr. Pritesh N. Patel ISTAR Page 27 <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <gradient android:startColor="#FFFF0000" android:endColor="#80FF00FF" android:angle="45"/> <padding android:left="7dp" android:top="7dp" android:right="7dp" android:bottom="7dp" /> <corners android:radius="8dp" /> </shape> This layout XML applies the shape drawable to a View: <TextView android:background="@drawable/gradient_box" android:layout_height="wrap_content" android:layout_width="wrap_content" /> This application code gets the shape drawable and applies it to a View: Resources res = getResources(); Drawable shape = res. getDrawable(R.drawable.gradient_box); TextView tv = (TextView)findViewByID(R.id.textview); tv.setBackground(shape);