The Android framework APIs provides a set 2D drawing APIs that allow you to render your owncustom graphics onto a canvas or to modify existing Views to customize their look and feel.When drawing 2D graphics, you'll typically do so in one of two ways:

  1. Draw your graphics or animations into a View object from your layout. In this manner, the drawing of your graphics is handled by the system's normal View hierarchy drawing process — you simply define the graphics to go inside the View.
  2. Draw your graphics directly to a Canvas. This way, you personally call the appropriate class's onDraw() method (passing it your Canvas), or one of the Canvasdraw...() 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 notneed to change dynamically and are not part of a performance-intensive game. For example, you shoulddraw your graphics into a View when you want to display a static graphic or predefined animation, withinan otherwise static application. Read Drawables for more information.

Option "b," drawing to a Canvas, is better when your application needs to regularly re-draw itself.Applications such as video games should be drawing to the Canvas on its own. However, there's more thanone 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()).

Draw with a Canvas


When you're writing an application in which you would like to perform specialized drawingand/or control the animation of graphics,you should do so by drawing through a Canvas. A Canvas works for you asa pretense, or interface, to the actual surface upon which your graphics will be drawn — itholds all of your "draw" calls. Via the Canvas, your drawing is actually performed upon anunderlying 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 Bitmapupon which drawing will actually be performed. The Bitmap is always required for a Canvas. You can set upa 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 yourBitmap to another Canvas with one of the Canvas.drawBitmap(Bitmap,...) methods. It's recommended that you ultimately draw your finalgraphics through a Canvas offered to youby View.onDraw() orSurfaceHolder.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 probablyhave some Drawable objects that you want to put on the Canvas. Drawablehas its own draw() methodthat takes your Canvas as an argument.

On a View

If your application does not require a significant amount of processing orframe-rate speed (perhaps for a chess game, a snake game,or another slowly-animated application), then you should consider creating a custom View componentand drawing with a Canvas in View.onDraw().The most convenient aspect of doing so is that the Android framework willprovide you with a pre-defined Canvas to which you will place your drawing calls.

To start, extend the View class (or descendant thereof) and definethe onDraw() callback method. This method will be called by the Androidframework to request that your View draw itself. This is where you will perform all your callsto draw through the Canvas, which is passed to you through the onDraw() callback.

The Android framework will only call onDraw() as necessary. Each time thatyour application is prepared to be drawn, you must request your View be invalidated by callinginvalidate(). This indicates that you'd like your View to be drawn andAndroid will then call your onDraw() method (though is not guaranteed that the callback willbe 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 thattake your Canvas as an argument. Once your onDraw() is complete, the Android framework willuse your Canvas to draw a Bitmap handled by the system.

Note: In order to request an invalidate from a thread other than your mainActivity's thread, you must call postInvalidate().

For information about extending the View class, readBuilding Custom Components.

For a sample application, see the Snake game, in the SDK samples folder:<your-sdk-directory>/samples/Snake/.

On a SurfaceView

The SurfaceView is a special subclass of View that offers a dedicateddrawing surface within the View hierarchy. The aim is to offer this drawing surface toan application's secondary thread, so that the application isn't requiredto wait until the system's View hierarchy is ready to draw. Instead, a secondary threadthat 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 alsoimplement SurfaceHolder.Callback. This subclass is an interface that will notify youwith 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 needto make adjustments based on new surface properties, and when to stop drawing and potentiallykill some tasks. Inside your SurfaceView class is also a good place to define your secondary Thread class, which willperform all the drawing procedures to your Canvas.

Instead of handling the Surface object directly, you should handle it viaa SurfaceHolder. So, when your SurfaceView is initialized, get the SurfaceHolder by callinggetHolder(). You should then notify the SurfaceHolder that you'dlike to receive SurfaceHolder callbacks (from SurfaceHolder.Callback) by callingaddCallback()(pass it this). Then override each of theSurfaceHolder.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 SurfaceHandlerand 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, callunlockCanvasAndPost(), passing ityour Canvas object. The Surface will now draw the Canvas as you left it. Perform this sequence of locking andunlocking 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 theentire surface. For example, you can clear the previous state of the Canvas by filling in a colorwith drawColor() or setting a background imagewith drawBitmap(). Otherwise,you will see traces of the drawings you previously performed.

For a sample application, see the Lunar Lander game, in the SDK samples folder:<your-sdk-directory>/samples/LunarLander/. Or,browse the source in the Sample Code section.

Drawables


Android offers a custom 2D graphics library for drawing shapes and images. The android.graphics.drawable package is where you'll find the common classes used for drawing in two-dimensions.

This document discusses the basics of using Drawable objects to draw graphics and how to use acouple subclasses of the Drawable class. For information on using Drawables to do frame-by-frameanimation, see DrawableAnimation.

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 ofdrawable graphics, including BitmapDrawable, ShapeDrawable, PictureDrawable,LayerDrawable, and several more. Of course, you can also extendthese 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 classconstructors. Below, we'll discuss each the first two techniques (using constructors is nothing newfor 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 othergraphics such as those used in a game.

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).

Note: Image resources placed in res/drawable/ may be automatically optimized with lossless image compression by the aapt tool during the build process. For example, a true-color PNG that does not require more than 256 colors may be converted to an 8-bit PNG with a color palette. This will result in an image of equal quality but which requires less memory. So be aware that the image binaries placed in this directory can change during the build. If you plan on reading an image as a bit stream in order to convert it to a bitmap, put your images in the res/raw/ folder instead, where they will not be optimized.

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);
 

Note: Each unique resource in your project can maintain onlyone state, no matter how many different objects you may instantiate for it. For example, if you instantiate two Drawable objects from the same image resource, then change a property (suchas the alpha) for one of the Drawables, then it will also affect the other. So when dealing withmultiple instances of an image resource, instead of directly transforming the Drawable, youshould perform a tweenanimation.

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:layout_height="wrap_content"
      android:tint="#55ff0000"
      android:src="@drawable/my_image"/>
 

For more information on using project resources, read about Resources and Assets.

Creating from resource XML

By now, you should be familiar with Android's principles of developing a User Interface. Hence, you understand thepower and flexibility inherent in defining objects in XML. This philosophy caries over from Viewsto Drawables. If there is a Drawable object that you'd like to create, which is not initiallydependent on variables defined by your application code or user interaction, then defining theDrawable in XML is a good option. Even if you expect your Drawable to change its propertiesduring the user's experience with your application, you should consider defining the object inXML, 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 examplebelow.)

Any Drawable subclass that supports the inflate() method can be defined in XML and instantiated by your application. Each Drawable that supports XML inflation utilizesspecific 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);
      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);

Refer to the Drawable classes listed above for more information on the XML attributessupported by each.

Shape Drawable


When you want to dynamically draw some two-dimensional graphics, a ShapeDrawable object will probably suit your needs. With a ShapeDrawable, you can programmatically draw primitive shapes and style them in any way imaginable.

A ShapeDrawable is an extension of Drawable, so you can useone where ever a Drawable is expected — perhaps for the background of a View, set with setBackgroundDrawable(). Of course, you can also draw your shape as its own custom View, to be added to your layout however you please. Because the ShapeDrawable has its own draw() method, you can create a subclass ofView that draws the ShapeDrawable during the View.onDraw() method. Here's a basic extension of the View class that does just this, to draw a ShapeDrawable as a View:

      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 the constructor, a ShapeDrawable is defines as an OvalShape. It's then given a color and the bounds of the shape are set. If you do not set the bounds,then the shape will not be drawn, whereas if you don't set the color, it will default to black.

With the custom View defined, it can be drawn any way you like. With the sample above, we can draw the shape programmatically in an Activity:

      CustomDrawableView mCustomDrawableView;

      protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      mCustomDrawableView = new CustomDrawableView(this);       setContentView(mCustomDrawableView);
      }
   

If you'd like to draw this custom drawable from the XML layout instead of from the Activity, then the CustomDrawable class must override the View(Context, AttributeSet) constructor, which is called when instantiating a View via inflation from XML. Then add a CustomDrawable element to the XML, like so:

      <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 properties of the drawable with public methods. Some properties you might want to adjust include alpha transparency, color filter, dither, opacity and color.

You can also define primitive drawable shapes using XML. For more information, see the section about Shape Drawables in the Drawable Resources document.

Nine-patch


A NinePatchDrawable graphic is a stretchable bitmapimage, which Android will automatically resize to accommodate the contents of the View in which you haveplaced it as the background. An example use of a NinePatch is the backgrounds used by standard Android buttons — buttons must stretch to accommodate strings of various lengths. A NinePatch drawable is astandard PNG image that includes an extra 1-pixel-wide border. It must be saved with the extension .9.png, and saved into the res/drawable/ directory of your project.

The border is used to define the stretchable and static areas of the image. You indicate a stretchable section by drawing one (or more) 1-pixel-wide black line(s) in the left and top part of the border (the other border pixels should be fully transparent or white). You can have as many stretchable sections as you want: their relative size stays the same, so the largest sections always remain the largest.

You can also define an optional drawable section of the image (effectively, the padding lines) by drawing a line on the right and bottom lines. If a View object sets the NinePatch as its background and then specifies the View's text, it will stretch itself so that all the text fits inside only the area designated by the right and bottom lines (if included). If the padding lines are not included, Android uses the left and top lines to define this drawable area.

To clarify the difference between the different lines, the left and top lines define which pixels of the image are allowed to be replicated in order to stretch the image. The bottom and right lines define the relative area within the image that the contents of the View are allowed to lie within.

Here is a sample NinePatch file used to define a button:

This NinePatch defines one stretchable area with the left and top lines and the drawable area with the bottom and right lines. In the top image, the dotted grey lines identify the regions of the image that will be replicated in order to stretch theimage. The pink rectangle in the bottom image identifies the region in which the contents of the View areallowed. If the contents don't fit in this region, then the image will be stretched so that theydo.

The Draw 9-patch tool offers an extremely handy way to create your NinePatch images, using a WYSIWYG graphics editor. Iteven raises warnings if the region you've defined for the stretchable area is at risk ofproducing drawing artifacts as a result of the pixel replication.

Example XML

Here's some sample layout XML that demonstrates how to add a NinePatch image to acouple of buttons. (The NinePatch image is saved asres/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 are set to "wrap_content" to make the button fit neatly around thetext.

Below are the two buttons rendered from the XML and NinePatch image shown above.Notice how the width and height of the button varies with the text, and the background imagestretches to accommodate it.

Android 官方文档:(一)动画和图像 —— 1.5 画布和画图的更多相关文章

  1. [翻译]Android官方文档 - 通知(Notifications)

    翻译的好辛苦,有些地方也不太理解什么意思,如果有误,还请大神指正. 官方文档地址:http://developer.android.com/guide/topics/ui/notifiers/noti ...

  2. Google Android官方文档进程与线程(Processes and Threads)翻译

    android的多线程在开发中已经有使用过了,想再系统地学习一下,找到了android的官方文档,介绍进程与线程的介绍,试着翻译一下. 原文地址:http://developer.android.co ...

  3. 学习android 官方文档

    9.29 1. 今天,FQ,看到android studio中文网上有一个FQ工具openVPN,我就使用了. 之前用过一个FQ工具开眼,但由于网速慢,我就弃用了. 2. 现在,我就可以FQ去andr ...

  4. Android官方文档

    下面的内容来自Android官方网站,由于访问这个网站需要FQ,不方便,所以我把部分内容copy下来了,不保证内容是最新的. Source Overview    Codelines, Branche ...

  5. android 官方文档 JNI TIPS

    文章地址  http://developer.android.com/training/articles/perf-jni.html JNI Tips JNI is the Java Native I ...

  6. Android 官方文档:(二)应用清单 —— 2.10 &lt;instrumentation&gt;标签

    syntax: <instrumentation android:functionalTest=["true" | "false"]           ...

  7. Android 官方文档:(二)应用清单 —— 2.2 &lt;action&gt;标签

    syntax: <action android:name="string" /> contained in: <intent-filter> descrip ...

  8. Android 官方文档:(二)应用清单 —— 2.26 &lt;uses-permission&gt;标签

    syntax: <uses-permission android:name="string"         android:maxSdkVersion="inte ...

  9. 【android官方文档】与其他App交互

    发送用户到另外一个App YOU SHOULD ALSO READ 内容分享 One of Android's most important features is an app's ability ...

随机推荐

  1. thinkphp框架if标签条件表达式

    eq 等于neq 不等于gt 大于egt 大于等于lt 小于elt 小于等于

  2. MySQL学习笔记:coalesce

    函数:coalesce 作用:返回传入的参数中第一个非NULL的值 ); # ); # 如果传入的参数所有都是NULL,则返回NULL,比如: SELECT COALESCE(NULL, NULL, ...

  3. MySQL 存储过程入门

    存储过程是带有逻辑的SQL语句,优点是执行效率高.缺点是可移植性差 1.存储过程语法 DELIMITER $ --声明结束符 CREATE PROCEDURE pro_test() --创建存储过程 ...

  4. JDBC连接池和DBUtils

    本节内容: JDBC连接池 DBUtils 一.JDBC连接池 实际开发中“获得连接”或“释放资源”是非常消耗系统资源的两个过程,为了解决此类性能问题,通常情况我们采取连接池技术,来共享连接Conne ...

  5. python学习day4之路文件的序列化和反序列化

    json和pickle序列化和反序列化 json是用来实现不同程序之间的文件交互,由于不同程序之间需要进行文件信息交互,由于用python写的代码可能要与其他语言写的代码进行数据传输,json支持所有 ...

  6. Codeforces Round #248 (Div. 1) D - Nanami's Power Plant 最小割

    D - Nanami's Power Plant 思路:类似与bzoj切糕那道题的模型.. #include<bits/stdc++.h> #define LL long long #de ...

  7. Vue学习笔记进阶篇——Render函数

    基础 Vue 推荐在绝大多数情况下使用 template 来创建你的 HTML.然而在一些场景中,你真的需要 JavaScript 的完全编程的能力,这就是 render 函数,它比 template ...

  8. Jersey入门三:创建一个JavaEE的Web项目

    1.在终端中输入如下命令,创建一个名为的simple-service-webapp项目: mvn archetype:generate -DarchetypeArtifactId=jersey-qui ...

  9. 基于spring-boot的应用程序的单元+集成测试方案

    目录 概述 概念解析 单元测试和集成测试 Mock和Stub 技术实现 单元测试 测试常规的bean 测试Controller 测试持久层 集成测试 从Controller开始测试 从中间层开始测试 ...

  10. Linux驱动之IIC总线

    <作用> 电子设备中有很多IIC设备之间需要进行相互通信,这样就产生了IIC总线,常用来实现设备之间的数据通信.   <IIC总线结构> IIC总线只有两条线,一条是串行数据线 ...