Android 官方文档:(一)动画和图像 —— 1.5 画布和画图
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:
- 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.
- 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
). In doing so, you are also in control of any animation.drawPicture()
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
and then handle theinvalidate()
callback.onDraw()
- 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 requestinvalidate()
).
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
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 onDraw()
,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 SurfaceHolder.lockCanvas()
Bitmap
upon 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
methods. It's recommended that you ultimately draw your finalgraphics through a Canvas offered to youby Canvas.drawBitmap(Bitmap,...)
orView.onDraw()
(see the following sections).SurfaceHolder.lockCanvas()
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
methodthat takes your Canvas as an argument.draw()
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
.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.View.onDraw()
To start, extend the View
class (or descendant thereof) and definethe
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 onDraw()
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 calling
. This indicates that you'd like your View to be drawn andAndroid will then call your invalidate()
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 calling
. You should then notify the SurfaceHolder that you'dlike to receive SurfaceHolder callbacks (from getHolder()
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
.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, calllockCanvas()
, 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.unlockCanvasAndPost()
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
or setting a background imagewith drawColor()
. Otherwise,you will see traces of the drawings you previously performed.drawBitmap()
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 画布和画图的更多相关文章
- [翻译]Android官方文档 - 通知(Notifications)
翻译的好辛苦,有些地方也不太理解什么意思,如果有误,还请大神指正. 官方文档地址:http://developer.android.com/guide/topics/ui/notifiers/noti ...
- Google Android官方文档进程与线程(Processes and Threads)翻译
android的多线程在开发中已经有使用过了,想再系统地学习一下,找到了android的官方文档,介绍进程与线程的介绍,试着翻译一下. 原文地址:http://developer.android.co ...
- 学习android 官方文档
9.29 1. 今天,FQ,看到android studio中文网上有一个FQ工具openVPN,我就使用了. 之前用过一个FQ工具开眼,但由于网速慢,我就弃用了. 2. 现在,我就可以FQ去andr ...
- Android官方文档
下面的内容来自Android官方网站,由于访问这个网站需要FQ,不方便,所以我把部分内容copy下来了,不保证内容是最新的. Source Overview Codelines, Branche ...
- android 官方文档 JNI TIPS
文章地址 http://developer.android.com/training/articles/perf-jni.html JNI Tips JNI is the Java Native I ...
- Android 官方文档:(二)应用清单 —— 2.10 <instrumentation>标签
syntax: <instrumentation android:functionalTest=["true" | "false"] ...
- Android 官方文档:(二)应用清单 —— 2.2 <action>标签
syntax: <action android:name="string" /> contained in: <intent-filter> descrip ...
- Android 官方文档:(二)应用清单 —— 2.26 <uses-permission>标签
syntax: <uses-permission android:name="string" android:maxSdkVersion="inte ...
- 【android官方文档】与其他App交互
发送用户到另外一个App YOU SHOULD ALSO READ 内容分享 One of Android's most important features is an app's ability ...
随机推荐
- Hexo命令无法找到 -问题修复
本人PC安装hexo按照官方npm方式下载: npm install -g hexo-cli 但是到了控制台,输入hexo总是无法找到该命令,提示:Command not Found!!!,无论git ...
- redis主从,哨兵(windows版)
一.下载 由于redis官方并不支持windows操作系统,所以官网上是下不到的,需要到gitlab上下载,下载地址如下: https://github.com/MicrosoftArchive/re ...
- python之路:python基础3
---恢复内容开始--- 本节内容 1. 函数基本语法及特性 2. 参数与局部变量 3. 返回值 嵌套函数 4.递归 5.匿名函数 6.函数式编程介绍 7.高阶函数 8.内置函数 温故知新 1. 集合 ...
- vue-cli中如何集成UEditor 富文本编辑器?
1.根据后台语言下载对应的editor插件版本 地址:https://ueditor.baidu.com/website/download.html 2.将下载好的资源放在/static/uedito ...
- spring boot 之使用mapstruct
最近在阅读swagger源码,当看到 springfox.documentation.swagger2.mappers.ModelMapper 类时,无意中看到该类上面使用的 org.mapstruc ...
- 编写一个简单的 JDBC 程序
连接数据库的步骤: 1.注册驱动(只做一次) 2.建立连接(Connection) 3.创建执行SQL的语句(Statement) 4.执行语句 5.处理执行结果(ResultSet) 6.释放资源 ...
- 8-2 Building for UN Uva1605
题意:你的任务是设计一个包含若干层的联合国大楼,其中每层都是一个等大的网络 由若干个国家需要在联合国大楼里面办公 你需要把每个格子分配给一个国家 使得任意两个不同的国家都有一对相邻的格子 (要没是同 ...
- MSTP多生成树的配置
STP的不足 STP协议虽然能够解决环路问题,但是由于网络拓扑收敛较慢,影响了用户通信质量 而且如果网络中的拓扑结构频繁变化,网络也会随之频繁失去连通性,从而导致用户通信频繁中断 RSTP对STP的改 ...
- python opencv3 cornerHarris 角点检测
git:https://github.com/linyi0604/Computer-Vision 角点也是处在一个无论框框往哪边移动 框框内像素值都会变化很大的情况而定下来的点 如果框框水平方向上移动 ...
- WinForm 使用 NPOI 2.2.1从datatable导出Excel
最新的NOPI应该是2.3了,但在官网上还是2.2.1. 也是第一次使用NPOI来导出Excel文件. 在写的时候搜不到2.2.1的教程,搜了一个2.2.0的教程. 不过也没什么问题,NPOI是真的方 ...