Android 2D Graphics

Source: Internet
Author: User
Tags xml example
Android provides an image library for Drawing Images and animation 2D. The two packages are android. graphics. drawable and android. view. animation, you can find the same class in the two packages to present two different aspects of the drawing and animation. This document describes how to use this library in your Android application. We will discuss how to draw a base class Drawable object, how to use a pair of Drawable subclasses, and how to create images and animations.

1 Drawable

Is a general abstract class, which aims to tell you what can be painted. You will find that various plotting classes are extended based on the Drawable class, including BitmapDrawable ShapeDrawable PictureDrawable LayerDrawable. Of course, you can inherit it to create your own drawing class. there are three ways to define and instantiate a Drawable, save an image to your project resources, use an XML file to describe the Drawable attribute, or use a normal class to construct it. The following two technologies will be discussed (for a developer with development experience, the construction is not the latest technology)

 

1.1 A simple method to create a resource image file is to add an image to your program and reference the file through the resource file. The Supported file types include PNG (preferred) JPG (acceptable) GIF (not recommended). Obviously, this is the preferred method for displaying the application icon and can also be used to display the LOGO, other images can be used in games, for example. Add an image resource to the res/drawable/directory of your project. From here, you can reference it to your code or your XML layout, another method is to reference it by using the resource number. For example, if you select a file, you only need to remove the suffix (for example, my_image.png references it as my_image)

1.2 since the creation of XML files, you should be familiar with developing a user interface based on Android principles. Therefore, you should also understand the role and flexibility of defining an XML file for objects. This idea is used for Drawables countless times. If you want to create a Drawable object that does not depend on variables or user exchanges, defining it in XML should be a good method. Even if you want to change its attributes in your application to increase the user experience. You should consider placing the object in XML, because you can modify its attributes at any time. When you define a Drawable in your XML file, save the XML file to the res/drawable directory in your project directory, and then call Resource. getDrawable () is used to retrieve and instantiate the resource ID in the XML file. Any Drawable subclass supports the inflate method, which will instantiate your program through XML. Any Drawable supports XML extension to use special XML attributes to help define object attributes. You can view any Drawable sub-class document to see how to define the XML file. The following XML defines TransitionDrawable:

 

<Transition xmlns: android = "http://schemas.android.com/apk/res/android">
<Item android: drawable = "@ drawable/image_expand">
<Item android: drawable = "@ drawable/image_collapse">

</Transition>


 2 ShapeDrawable

When you want to draw some dynamic two-dimensional images, a ShapeDrawable object may be of great help to you. Through ShapeDrawable, you can program to draw any image and style you think of. ShapeDrawable inherits Drawable, so you can call some functions in Drawable, such as the view background, set through setBackgroundDrawable. Of course, you can draw your image in a custom view layout, because ShapeDrawable has its own draw () method. You can create a subclass of a View to draw ShapeDrawable during the View. OnDraw () method. This is a basic view extension class to draw ShapeDrawable

 

Public class CustomDrawableView extends View {
Private ShapeDrawable mDrawable;
Public CustomDrawableView (Context context ){
Super (context );
Int x = 10;
Int y = 10;
Int width = 300;
Int height = 50;
MDrawable = new ShapeDrawable (new OvalShape ());
MDrawable. getPaint (). setColor (0xff74AC23 );
MDrawable. setBounds (x, y, x + width, y + height );
}
Protected void onDraw (Canvas canvas ){
MDrawable. draw (canvas );
}
}

 

In this constructor, ShapeDrawable defines an ovalShape type and then sets the color and boundary. If you do not set the boundary, this image will not be drawn. However, if you do not set the color, it is black by default. Through the custom view, you can draw your favorite stuff through various methods. Below is a simple example.

 

CustomDrawableView mCustomDrawableView;
Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
MCustomDrawableView = new CustomDrawableView (this );
SetContentView (mCustomDrawableView );
}

 

If you want to use XML file configuration to replace the original layout to draw custom drawable, your custom Drawable class must overload the view (Context, AttributeSet) constructor. The following is an example:

 

<Com. example. shapedrawable. CustomDrawableView
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"/>

The ShapeDrawable class (like many other Drawable types in the android. graphics. drawable package) allows you to define various attributes of the drawable public method. You can adjust some attributes, including transparency, color filtering, opacity, and color.

 

3 NinePatchDrawableNinePatchDrawable draws a scalable bitmap image. Android automatically adjusts the size to accommodate the displayed content. And keep it to the res/drawable directory of the project. This boundary is used to determine the scalable and static areas of an image. You can draw one or more black pixels on the left and above to point out the Scalable part (you can need a lot of scalable parts). The relative position is the same as that of the Scalable part, so the big part is always very big.

 

You can also draw an optional drawable area (valid, padding) on the Right and bottom of the image ). If your view object sets NinePath as the background and then specifies a special view font, it automatically scales all the text to adapt to the area designed based on the right and bottom lines (if any ), of course, the padding line is not included. Android can use the line on the left and the line above to define a drawable area. Let's clarify these two different lines. The lines on the left and top define which pixels of the image can be copied during scaling. The bottom line and the right line are used to define an image in a relative position, and the View content is placed in it. The following is an example of using the NinePatch file to define a button. NinePath defines a scalable area through the line on the left and the line on the top, while the line on the bottom and the line on the right can define a printable area. In the above picture, the line of the gray point defines the area of the image. For image scaling, the pink rectangle at the bottom of the image defines the area that is allowed to be presented within the view. If the content is not suitable for this difference, they will stretch the image.

 

The Draw9-path tool provides a very simple way to create your NinePath image ,. using the WYSIWY graphic editor, if the area you define is scalable, the area may be out of the scope of the drawing and it may even give a warning. The following is a simple XML example to demonstrate how to add NinePatch (the NinePath image is saved in res/drawable/my_button_background.9.png

 

<Button id = "@ + id/tiny"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: layout_alignParentTop = "true"
Android: layout_centerInParent = "true"
Android: text = "Tiny"
Android: textSize = "8sp"
Android: background = "@ drawable/my_button_background"/>
<Button id = "@ + id/big"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: layout_alignParentBottom = "true"
Android: layout_centerInParent = "true"
Android: text = "Biiiiiiig text! "
Android: textSize = "30sp"
Android: background = "@ drawable/my_button_background"/>

 

Note that the width and height must be set to wrap_content to make the button suitable for text.

 

The following two buttons are based on the XML and NinePath images. As the buttons change through the text size, the background image will also adapt.

 

4 Tween Animation

A tween animation performs a series of simple conversions (location, size, rotation, transparency) on the content of the view object ). If you have a text view object, you can move it, rotate it, and make it larger or smaller. If there is a background image under the text, the background image will also be converted with the file. The Animation package provides all the classes for tween Animation. Tween animation defines an animation command queue, which can be defined in XML or Android Code. For example, we recommend that you use XML to define the layout, because of its reading and reusability, it can exchange more than hard encoding. In the following example, we use XML (refer to the AnimationSet class or other animation classes to learn how to define in Code) to define what type of conversion you want, when they happen, how long should they be executed? The conversion can be continuous or at the same time. For example, if you want to move the text content from the left to the right, then rotate the text 180 degrees, or rotate the text content simultaneously during the movement, no conversion requires some special parameters (size changes of the start and end sizes, rotation angles of the start and end, etc., you can also set some basic parameters (for example, if several conversions occur simultaneously, you can set the same Start Time for them. If the conversion is based on the sequence, the calculation Start Time plus the cycle. The XML file of the animation is still in the res/anim directory of your project. This file must contain a root element, you can set <alpha> <scale> <translate> <rotate> interpolation element or add all the above elements to the <set> element group. By default, therefore, all animation commands occur at the same time. In order to enable them to occur in sequence, you need to set a special attribute startOffset. The following example will demonstrate. The following ApiDemos XML file defines the scaling function of the view object and rotates at the same time.

<Set android: Using interpolator = "false"> <scale
Android: interpolator = "@ android: anim/
Accelerate_decelerate_interpolator"
Android: fromXScale = "1.0"
Android: toXScale = "1.4"
Android: fromYScale = "1.0"
Android: toYScale = "0.6"
Android: Required Tx = "50%"
Android: Ty = "50%"
Android: fillAfter = "false"
Android: duration = "700"/>
<Set android: interpolator = "@ android: anim/decelerate_interpolator">
<Scale
Android: fromXScale = "1.4"
Android: toXScale = "0.0"
Android: fromYScale = "0.6"
Android: toYScale = "0.0"
Android: Required Tx = "50%"
Android: Ty = "50%"
Android: startOffset = "700"
Android: duration= "400"
Android: fillBefore = "false"/>
<Rotate
Android: fromDegrees = "0"
Android: toDegrees = "-45"
Android: toYScale = "0.0"
Android: Required Tx = "50%"
Android: Ty = "50%"
Android: startOffset = "700"
Android: duration = "400"/>
</Set>


The screen coordinate (not used in this example) is (0, 0) in the upper left corner and increases to the right. There are also many values, such as whether the specified object is relative to itself or the parent class. You must set it in the correct format ("50" is relative to the parent class 50% "50%" relative to your % 50). You can decide how to transform to apply the specified interpolation for a period of time, android includes several interpolation sub-classes to specify different velocity curves. For example, AccelerateInterpolator tells you that the start is slow and the speed is slow. Each of them has a property value that can be used in XML. Save hyperspace_jump.xml to the res/anim directory in your project. The following JAVA code will reference it to layout an ImageView object.

 

ImageView spaceshipImage = (ImageView) findViewById (R. id. spaceshipImage );
Animation hyperspaceJumpAnimation = AnimationUtils. loadAnimation (this,
R. anim. hyperspace_jump );
SpaceshipImage. startAnimation (hyperspaceJumpAnimation );

 

As an alternative to startAnimation (), you can use Animation. setStartTime to define the start time, through view. setAnimationl is used to specify an animation tag for the XML parameter attribute. For details, refer to the animation discussion in Available Resources.

 

NOTE: If your animation moves or adjusts the size regardless of the consequences, the view will not adapt to your animation. Even so, the animation will be out of the view range, but will not be truncated, however, truncation occurs when your animation exceeds the parent Class View.

 

5 Frame Animation

Creating a sequence of different images is a traditional animation scenario. It is played according to instructions, just like a rolling movie. In Android, the basic class AnimationDrawable is dedicated to frame animation.

 

Although you can define Frame Animation in code, you can use the API of the AnimationDrawable class ., it is very simple to list all frames in an animation through an XML file, such as the animation tween above. The XML file of this category animation is placed in the res/anim directory of the project. In this case, the instruction executes each frame of animation according to the cycle. The XML file contains an <animation-list> root node element and several sub-nodes <item> to define each frame. A resource defines the frame name and duration respectively. The following is an example:

 

<Animation-list xmlns: android = "http://schemas.android.com/apk/res/android" android: oneshot = "true">
<Item android: drawable = "@ drawable/rocket_thrust1"
Android: duration = "200"/>
<Item android: drawable = "@ drawable/rocket_thrust2"
Android: duration = "200"/>
<Item android: drawable = "@ drawable/rocket_thrust3"
Android: duration = "200"/>
</Animation-list>

 

This animation plays three frames. By setting the android: oneshot attribute to true, it will stop at the last frame. If it is set to false, the animation will be played cyclically. Save this file to the project directory res/anim, Which is rocket_thrust.xml. You can also add a background image to the view and start playing. The following is an example:

 

AnimationDrawable rocketAnimation;

Publicvoid onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
ImageView rocketImage = (ImageView) findViewById (R. id. rocket_image );
RocketImage. setBackgroundResource (R. anim. rocket_thrust );
RocketAnimation = (AnimationDrawable) rocketImage. getBackground ();
}
Public boolean onTouchEvent (MotionEvent event ){
If (event. getAction () = MotionEvent. ACTION_DOWN ){
RocketAnimation. start ();
Return true;
}
Return super. onTouchEvent (event );
}

 

Note that you cannot call start () when calling onCreate () in AnimationDrawable because AnimationDrawable cannot run in an incomplete window, if you want to play an animation immediately without any interaction, you can call it in the onWindowFocusChanged () method. In this way, it will become the focus of the window.

 

Complete. Pai_^

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.