diff --git a/docs/html/guide/topics/graphics/2d-graphics.jd b/docs/html/guide/topics/graphics/2d-graphics.jd index 618cdf8c71308..ac2b47c5c3c52 100644 --- a/docs/html/guide/topics/graphics/2d-graphics.jd +++ b/docs/html/guide/topics/graphics/2d-graphics.jd @@ -1,296 +1,484 @@ -page.title=2D Graphics +page.title=Canvas and Drawables parent.title=Graphics parent.link=index.html @jd:body -
Android offers a custom 2D graphics library for drawing and animating shapes and images. -The {@link android.graphics.drawable} and {@link android.view.animation} -packages are where you'll find the common classes used for drawing and animating in two-dimensions. +
The Android framework APIs provides a set 2D drawing APIs that allow you to render your own +custom 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...() methods (like
+ {@link android.graphics.Canvas#drawPicture(Picture,Rect) 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. Read Drawables for more information.
-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).
+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 than +one way to do this:
+{@link android.view.View#invalidate()} and then handle the
+ {@link android.view.View#onDraw(Canvas) onDraw()} callback.invalidate()).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 {@link android.graphics.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 {@link android.graphics.Bitmap}, which is placed into the window.
+ +In the event that you're drawing within the {@link android.view.View#onDraw(Canvas) 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 {@link android.view.SurfaceHolder#lockCanvas() 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 {@link android.graphics.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 {@link android.graphics.Canvas#drawBitmap(Bitmap,Matrix,Paint)
+Canvas.drawBitmap(Bitmap,...)} methods. It's recommended that you ultimately draw your final
+graphics through a Canvas offered to you
+by {@link android.view.View#onDraw(Canvas) View.onDraw()} or
+{@link android.view.SurfaceHolder#lockCanvas() SurfaceHolder.lockCanvas()} (see the following sections).
The {@link android.graphics.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 {@link android.graphics.drawable.Drawable} objects that you want to put on the Canvas. Drawable
+has its own {@link android.graphics.drawable.Drawable#draw(Canvas) draw()} method
+that takes your Canvas as an argument.
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 {@link android.view.View#onDraw(Canvas) 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 {@link android.view.View} class (or descendant thereof) and define
+the {@link android.view.View#onDraw(Canvas) 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 your calls
+to draw through the {@link android.graphics.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
+{@link android.view.View#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 {@link android.view.View#postInvalidate()}.
Also read Building Custom Components +for a guide to extending a View class, and 2D Graphics: Drawables for +information on using Drawable objects like images from your resources and other primitive shapes.
+ +For a sample application, see the Snake game, in the SDK samples folder:
+<your-sdk-directory>/samples/Snake/.
The {@link android.view.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 {@link android.view.SurfaceView}. The class should also +implement {@link android.view.SurfaceHolder.Callback}. This subclass is an interface that will notify you +with information about the underlying {@link android.view.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 {@link android.view.SurfaceHolder}. So, when your SurfaceView is initialized, get the SurfaceHolder by calling
+{@link android.view.SurfaceView#getHolder()}. You should then notify the SurfaceHolder that you'd
+like to receive SurfaceHolder callbacks (from {@link android.view.SurfaceHolder.Callback}) by calling
+{@link android.view.SurfaceHolder#addCallback(SurfaceHolder.Callback) addCallback()}
+(pass it this). Then override each of the
+{@link android.view.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 {@link android.view.SurfaceHolder#lockCanvas() 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
+{@link android.view.SurfaceHolder#unlockCanvasAndPost(Canvas) unlockCanvasAndPost()}, passing it
+your Canvas object. The Surface will now draw 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 {@link android.graphics.Canvas#drawColor(int) drawColor()} or setting a background image
+with {@link android.graphics.Canvas#drawBitmap(Bitmap,Rect,RectF,Paint) 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.
Android offers a custom 2D graphics library for drawing shapes and images. + The {@link android.graphics.drawable} package is where you'll find the common classes used for + drawing in two-dimensions.
-A {@link android.graphics.drawable.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 {@link android.graphics.drawable.BitmapDrawable}, {@link android.graphics.drawable.ShapeDrawable}, -{@link android.graphics.drawable.PictureDrawable}, {@link android.graphics.drawable.LayerDrawable}, and several more. -Of course, you can also extend these to define your own custom Drawable objects that behave in unique ways.
+This document discusses the basics of using Drawable objects to draw graphics and how to use a +couple subclasses of the Drawable class. For information on using Drawables to do frame-by-frame +animation, see Frame-by-Frame +Animation.
-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).
+A {@link android.graphics.drawable.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 {@link android.graphics.drawable.BitmapDrawable}, {@link + android.graphics.drawable.ShapeDrawable}, {@link android.graphics.drawable.PictureDrawable}, +{@link android.graphics.drawable.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).
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.
+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.
-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).
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.
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.
The following code snippet demonstrates how to build an {@link android.widget.ImageView} that uses an image -from drawable resources and add it to the layout.
+The following code snippet demonstrates how to build an {@link android.widget.ImageView} that + uses an image from drawable resources and add it to the layout.
-LinearLayout mLinearLayout;
+ LinearLayout mLinearLayout;
-protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
- // Create a LinearLayout in which to add the ImageView
- mLinearLayout = new LinearLayout(this);
+ // 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));
+ // 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 -{@link android.graphics.drawable.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); + // 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 + {@link android.graphics.drawable.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 only one -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 (such as the alpha) for one of the -Drawables, then it will also affect the other. So when dealing with multiple instances of an image resource, -instead of directly transforming the Drawable, you should perform a tween animation.
+Note: Each unique resource in your project can maintain only +one 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 (such +as the alpha) for one of the Drawables, then it will also affect the other. So when dealing with +multiple instances of an image resource, instead of directly transforming the Drawable, you +should perform a tween +animation.
-The XML snippet below shows how to add a resource Drawable to an -{@link android.widget.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.
+The XML snippet below shows how to add a resource Drawable to an + {@link android.widget.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.
-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.
+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
-{@link android.content.res.Resources#getDrawable(int) Resources.getDrawable()}, passing it the resource ID
-of your XML file. (See the example below.)
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
+ {@link android.content.res.Resources#getDrawable(int) 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.
+
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.
-
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> -+
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);+
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 attributes supported by each.
+Refer to the Drawable classes listed above for more information on the XML attributes +supported by each.
-When you want to dynamically draw some two-dimensional graphics, a {@link android.graphics.drawable.ShapeDrawable} -object will probably suit your needs. With a ShapeDrawable, you can programmatically draw -primitive shapes and style them in any way imaginable.
+When you want to dynamically draw some two-dimensional graphics, a {@link + android.graphics.drawable.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 {@link android.graphics.drawable.Drawable}, so you can use one where ever
-a Drawable is expected — perhaps for the background of a View, set with
-{@link android.view.View#setBackgroundDrawable(android.graphics.drawable.Drawable) setBackgroundDrawable()}.
-Of course, you can also draw your shape as its own custom {@link android.view.View},
-to be added to your layout however you please.
-Because the ShapeDrawable has its own draw() method, you can create a subclass of View 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;
+ A ShapeDrawable is an extension of {@link android.graphics.drawable.Drawable}, so you can use
+one where ever
+ a Drawable is expected — perhaps for the background of a View, set with
+ {@link android.view.View#setBackgroundDrawable(android.graphics.drawable.Drawable)
+ setBackgroundDrawable()}.
+ Of course, you can also draw your shape as its own custom {@link android.view.View},
+ to be added to your layout however you please.
+ Because the ShapeDrawable has its own draw() method, you can create a subclass of
+View 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);
+ public CustomDrawableView(Context context) {
+ super(context);
- int x = 10;
- int y = 10;
- int width = 300;
- int height = 50;
+ 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);
- }
+ 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);
- }
-}
-
+ protected void onDraw(Canvas canvas) {
+ mDrawable.draw(canvas);
+ }
+ }
+
-In the constructor, a ShapeDrawable is defines as an {@link android.graphics.drawable.shapes.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; +-In the constructor, a ShapeDrawable is defines as an {@link + android.graphics.drawable.shapes.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); -} -+ protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + mCustomDrawableView = new CustomDrawableView(this); -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 {@link android.view.View#View(android.content.Context, android.util.AttributeSet) 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" - /> -+ setContentView(mCustomDrawableView); + } +
The ShapeDrawable class (like many other Drawable types in the {@link 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.
+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 {@link + android.view.View#View(android.content.Context, android.util.AttributeSet) 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 {@link +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 You can also define primitive drawable shapes using XML. For more information, see the -section about Shape Drawables in the Drawable Resources -document.
+ document. - +A StateListDrawable is an extension of the DrawableContainer class, making it little +different. + The primary distinction is that the + StateListDrawable manages a collection of images for the Drawable, instead of just one. + This means that it can switch the image when you want, without switching objects. However, +the + intention of the StateListDrawable is to automatically change the image used based on the +state + of the object it's attached to. + --> -
A {@link android.graphics.drawable.NinePatchDrawable} graphic is a stretchable bitmap image, which Android
-will automatically resize to accommodate the contents of the View in which you have placed 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 a standard 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: -
-
+ A {@link android.graphics.drawable.NinePatchDrawable} graphic is a stretchable bitmap
+image, which Android
+ will automatically resize to accommodate the contents of the View in which you have
+placed 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 a
+standard 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 the image. The pink -rectangle in the bottom image identifies the region in which the contents of the View are allowed. -If the contents don't fit in this region, then the image will be stretched so that they do. +
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 the +image. The pink + rectangle in the bottom image identifies the region in which the contents of the View are +allowed. + If the contents don't fit in this region, then the image will be stretched so that they +do.
-The Draw 9-patch tool offers - an extremely handy way to create your NinePatch images, using a WYSIWYG graphics editor. It +
The Draw 9-patch tool offers + an extremely handy way to create your NinePatch images, using a WYSIWYG graphics editor. It even raises warnings if the region you've defined for the stretchable area is at risk of producing drawing artifacts as a result of the pixel replication.
@@ -298,7 +486,8 @@ producing drawing artifacts as a result of the pixel replication.Here's some sample layout XML that demonstrates how to add a NinePatch image to a
-couple of buttons. (The NinePatch image is saved as res/drawable/my_button_background.9.png
+couple of buttons. (The NinePatch image is saved as
+res/drawable/my_button_background.9.png
<Button id="@+id/tiny"
android:layout_width="wrap_content"
@@ -318,11 +507,12 @@ couple of buttons. (The NinePatch image is saved as res/drawable/my_button
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 the text. +
Note that the width and height are set to "wrap_content" to make the button fit neatly around the +text.
-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 image +
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 image stretches to accommodate it.
diff --git a/docs/html/guide/topics/graphics/hardware-accel.jd b/docs/html/guide/topics/graphics/hardware-accel.jd new file mode 100644 index 0000000000000..c8703a5f0f03d --- /dev/null +++ b/docs/html/guide/topics/graphics/hardware-accel.jd @@ -0,0 +1,522 @@ +page.title=Hardware Acceleration +parent.title=Graphics +parent.link=index.html +@jd:body + + +Beginning in Android 3.0 (API level 11), the Android 2D rendering pipeline is designed to + better support hardware acceleration. Hardware acceleration carries out all drawing operations + that are performed on a {@link android.view.View}'s canvas using the GPU.
+ +The easiest way to enable hardware acceleration is to turn it on + globally for your entire application. If your application uses only standard views and {@link + android.graphics.drawable.Drawable}s, turning it on globally should not cause any adverse + effects. However, because hardware acceleration is not supported for all of the 2D drawing + operations, turning it on might affect some of your applications that use custom views or drawing + calls. Problems usually manifest themselves as invisible elements, exceptions, or wrongly + rendered pixels. To remedy this, Android gives you the option to enable or disable hardware + acceleration at the following levels:
+ +If your application performs custom drawing, test your application on actual hardware +devices with hardware acceleration turned on to find any problems. The Unsupported drawing operations section describes known issues with +drawing operations that cannot be hardware accelerated and how to work around them.
+ + +You can control hardware acceleration at the following levels:
+In your Android manifest file, add the following attribute to the
+
+ <application> tag to enable hardware acceleration for your entire
+ application:
+<application android:hardwareAccelerated="true" ...> ++ +
If your application does not behave properly with hardware acceleration turned on globally,
+ you can control it for individual activities as well. To enable or disable hardware acceleration
+ at the activity level, you can use the android:hardwareAccelerated
+ attribute for the
+ <activity> element. The following example enables hardware acceleration
+for the entire application but disables it for one activity:
+<application android:hardwareAccelerated="true"> + <activity ... /> + <activity android:hardwareAccelerated="false" /> +</application> ++ +
If you need even more fine-grained control, you can enable hardware acceleration for a given + window with the following code:
+ ++getWindow().setFlags( + WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED, + WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED); + ++ +
Note: You currently cannot disable hardware acceleration at +the window level.
+ +You can disable hardware acceleration for an individual view at runtime with the +following code:
+ ++myView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); ++ +
Note: You currently cannot enable hardware acceleration at +the view level. View layers have other functions besides disabling hardware acceleration. See View layers for more information about their uses.
+ +It is sometimes useful for an application to know whether it is currently hardware + accelerated, especially for things such as custom views. This is particularly useful if your + application does a lot of custom drawing and not all operations are properly supported by the new + rendering pipeline.
+ +There are two different ways to check whether the application is hardware accelerated:
+ +true if the {@link android.view.View} is attached to a hardware accelerated
+ window.true if the {@link android.graphics.Canvas} is hardware acceleratedIf you must do this check in your drawing code, use {@link + android.graphics.Canvas#isHardwareAccelerated Canvas.isHardwareAccelerated()} instead of {@link + android.view.View#isHardwareAccelerated View.isHardwareAccelerated()} when possible. When a view + is attached to a hardware accelerated window, it can still be drawn using a non-hardware + accelerated Canvas. This happens, for instance, when drawing a view into a bitmap for caching + purposes.
+ + +When hardware acceleration is enabled, the Android framework utilizes a new drawing model that + utilizes display lists to render your application to the screen. To fully understand + display lists and how they might affect your application, it is useful to understand how Android + draws views without hardware acceleration as well. The following sections describe the + software-based and hardware-accelerated drawing models.
+ +In the software drawing model, views are drawn with the following two steps:
+Whenever an application needs to update a part of its UI, it invokes {@link + android.view.View#invalidate invalidate()} (or one of its variants) on any view that has changed + content. The invalidation messages are propagated all the way up the view hierarchy to compute + the regions of the screen that need to be redrawn (the dirty region). The Android system then + draws any view in the hierarchy that intersects with the dirty region. Unfortunately, there are + two drawbacks to this drawing model:
+Note: Android views automatically call {@link + android.view.View#invalidate invalidate()} when their properties change, such as the background + color or the text in a {@link android.widget.TextView}.
+ +The Android system still uses {@link android.view.View#invalidate invalidate()} and {@link + android.view.View#draw draw()} to request screen updates and to render views, but handles the + actual drawing differently. Instead of executing the drawing commands immediately, the Android + system records them inside display lists, which contain the output of the view hierarchy’s + drawing code. Another optimization is that the Android system only needs to record and update + display lists for views marked dirty by an {@link android.view.View#invalidate invalidate()} + call. Views that have not been invalidated can be redrawn simply by re-issuing the previously + recorded display list. The new drawing model contains three stages:
+ +With this model, you cannot rely on a view intersecting the dirty region to have its {@link + android.view.View#draw draw()} method executed. To ensure that the Android system records a + view’s display list, you must call {@link android.view.View#invalidate invalidate()}. Forgetting + to do so causes a view to look the same even after changing it, which is an easier bug to find if + it happens.
+ +Using display lists also benefits animation performance because setting specific properties, + such as alpha or rotation, does not require invalidating the targeted view (it is done + automatically). This optimization also applies to views with display lists (any view when your + application is hardware accelerated.) For example, assume there is a {@link + android.widget.LinearLayout} that contains a {@link android.widget.ListView} above a {@link + android.widget.Button}. The display list for the {@link android.widget.LinearLayout} looks like + this:
+ +Assume now that you want to change the {@link android.widget.ListView}'s opacity. After
+ invoking setAlpha(0.5f) on the {@link android.widget.ListView}, the display list now
+ contains this:
The complex drawing code of {@link android.widget.ListView} was not executed. Instead, the + system only updated the display list of the much simpler {@link android.widget.LinearLayout}. In + an application without hardware acceleration enabled, the drawing code of both the list and its + parent are executed again.
+ +When hardware accelerated, the 2D rendering pipeline supports the most commonly used {@link + android.graphics.Canvas} drawing operations as well as many less-used operations. All of the + drawing operations that are used to render applications that ship with Android, default widgets + and layouts, and common advanced visual effects such as reflections and tiled textures are + supported. The following list describes known operations that are not supported + with hardware acceleration:
+ +In addition, some operations behave differently with hardware acceleration enabled:
+ +XOR,
+ Difference and ReverseDifference clip modes are ignored. 3D
+ transforms do not apply to the clip rectangleIf your application is affected by any of these missing features or limitations, you can turn + off hardware acceleration for just the affected portion of your application by calling + {@link android.view.View#setLayerType setLayerType(View.LAYER_TYPE_SOFTWARE, null)}. This way, +you can still take advantage of hardware acceleratin everywhere else. See Controlling Hardware Acceleration for more information on how to enable and +disable hardware acceleration at different levels in your application. + + + +
In all versions of Android, views have had the ability to render into off-screen buffers,
+either by using a view's drawing cache, or by using {@link android.graphics.Canvas#saveLayer
+ Canvas.saveLayer()}. Off-screen buffers, or layers, have several uses. You can use them to get
+ better performance when animating complex views or to apply composition effects. For instance,
+ you can implement fade effects using Canvas.saveLayer() to temporarily render a view
+ into a layer and then composite it back on screen with an opacity factor.
Beginning in Android 3.0 (API level 11), you have more control on how and when to use layers + with the {@link android.view.View#setLayerType View.setLayerType()} method. This API takes two + parameters: the type of layer you want to use and an optional {@link android.graphics.Paint} + object that describes how the layer should be composited. You can use the {@link + android.graphics.Paint} parameter to apply color filters, special blending modes, or opacity to a + layer. A view can use one of three layer types:
+ +The type of layer you use depends on your goal:
+ +Hardware layers can deliver faster and smoother animations when your application +is hardware accelerated. Running an animation at 60 frames per second is not always possible when +animating complex views that issue a lot of drawing operations. This can be alleviated by +using hardware layers to render the view to a hardware texture. The hardware texture can +then be used to animate the view, eliminating the need for the view to constantly redraw itself +when it is being animated. The view is not redrawn unless you change the view's +properties, which calls {@link android.view.View#invalidate invalidate()}, or if you call {@link +android.view.View#invalidate invalidate()} manually. If you are running an animation in +your application and do not obtain the smooth results you want, consider enabling hardware layers on +your animated views.
+ +When a view is backed by a hardware layer, some of its properties are handled by the way the + layer is composited on screen. Setting these properties will be efficient because they do not + require the view to be invalidated and redrawn. The following list of properties affect the way + the layer is composited. Calling the setter for any of these properties results in optimal + invalidation and no redrawing of the targeted view:
+ +alpha: Changes the layer's opacityx, y, translationX, translationY:
+Changes the layer's positionscaleX, scaleY: Changes the layer's sizerotation, rotationX, rotationY: Changes the
+ layer's orientation in 3D spacepivotX, pivotY: Changes the layer's transformations originThese properties are the names used when animating a view with an {@link + android.animation.ObjectAnimator}. If you want to access these properties, call the appropriate + setter or getter. For instance, to modify the alpha property, call {@link + android.view.View#setAlpha setAlpha()}. The following code snippet shows the most efficient way + to rotate a viewiew in 3D around the Y-axis:
++view.setLayerType(View.LAYER_TYPE_HARDWARE, null); +ObjectAnimator.ofFloat(view, "rotationY", 180).start(); ++ +
Because hardware layers consume video memory, it is highly recommended that you enable them +only for the duration of the animation and then disable them after the animation is done. You +can accomplish this using animation listeners:
+
+View.setLayerType(View.LAYER_TYPE_HARDWARE, null);
+ObjectAnimator animator = ObjectAnimator.ofFloat(view, "rotationY", 180);
+animator.addListener(new AnimatorListenerAdapter() {
+ @Override
+ public void onAnimationEnd(Animator animation) {
+ view.setLayerType(View.LAYER_TYPE_NONE, null);
+ }
+});
+animator.start();
+
+
+ For more information on property animation, see Property Animation.
+ +Switching to hardware accelerated 2D graphics can instantly increase performance, but you + should still design your application to use the GPU effectively by following these + recommendations:
+ +LAYER_TYPE_HARDWARE.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. The most -common 2D graphics APIs can be found in the {@link android.graphics.drawable drawable package}. -OpenGL APIs are available from the Khronos {@link javax.microedition.khronos.opengles OpenGL ES} and -the {@link android.opengl} packages. The RenderScript APIs are available in the -{@link android.renderscript} package.
- -When starting a project, it's important to consider exactly what your graphical demands will be. +
When writing an application, it's important to consider exactly what your graphical demands will be. Varying graphical tasks are best accomplished with varying techniques. For example, graphics and animations for a rather static application should be implemented much differently than graphics and animations -for an interactive game or 3D rendering.
- -Here, we'll discuss a few of the options you have for drawing graphics on Android, -and which tasks they're best suited for.
- -If you're specifically looking for information on drawing 3D graphics, this page won't -help a lot. However, the information below about how to Draw with a -Canvas (and the section on SurfaceView), will give you a quick idea of how you should draw to -the View hierarchy. For more information on Android's 3D graphics APIs, see -the 3D with OpenGL and -RenderScript documents.
- - -When drawing 2D graphics, you'll typically do so in one of two ways:
-draw() method (passing it your Canvas), or one of the Canvas draw...() methods (like
- {@link android.graphics.Canvas#drawPicture(Picture,Rect) 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. Read Simple Graphics Inside a View. - -
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:
-{@link android.view.View#invalidate()} and then handle the
- {@link android.view.View#onDraw(Canvas) onDraw()} callback..invalidate())....Begin by reading Draw with a Canvas.
- -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 {@link android.widget.ImageView} in your layout. -In this case, you can skip the rest of this document and learn how to -draw graphics and animations in the 2D Graphics document. +for an interactive game. Here, we'll discuss a few of the options you have for drawing graphics +on Android and which tasks they're best suited for.
+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 {@link android.graphics.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 {@link android.graphics.Bitmap}, which is placed into the window.
- -In the event that you're drawing within the {@link android.view.View#onDraw(Canvas) 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 {@link android.view.SurfaceHolder#lockCanvas() 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 {@link android.graphics.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 {@link android.graphics.Canvas#drawBitmap(Bitmap,Matrix,Paint)
-Canvas.drawBitmap(Bitmap,...)} methods. It's recommended that you ultimately draw your final
-graphics through a Canvas offered to you
-by {@link android.view.View#onDraw(Canvas) View.onDraw()} or
-{@link android.view.SurfaceHolder#lockCanvas() SurfaceHolder.lockCanvas()} (see the following sections).
The {@link android.graphics.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 {@link android.graphics.drawable.Drawable} objects that you want to put on the Canvas. Drawable
-has its own {@link android.graphics.drawable.Drawable#draw(Canvas) draw()} method
-that takes your Canvas as an argument.
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 {@link android.view.View#onDraw(Canvas) 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 {@link android.view.View} class (or descendant thereof) and define
-the {@link android.view.View#onDraw(Canvas) 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 your calls
-to draw through the {@link android.graphics.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
-{@link android.view.View#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 {@link android.view.View#postInvalidate()}.
Also read Custom Components -for a guide to extending a View class, and 2D Graphics: Drawables for -information on using Drawable objects like images from your resources and other primitive shapes.
- -For a sample application, see the Snake game, in the SDK samples folder:
-<your-sdk-directory>/samples/Snake/.
The {@link android.view.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 {@link android.view.SurfaceView}. The class should also -implement {@link android.view.SurfaceHolder.Callback}. This subclass is an interface that will notify you -with information about the underlying {@link android.view.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 {@link android.view.SurfaceHolder}. So, when your SurfaceView is initialized, get the SurfaceHolder by calling
-{@link android.view.SurfaceView#getHolder()}. You should then notify the SurfaceHolder that you'd
-like to receive SurfaceHolder callbacks (from {@link android.view.SurfaceHolder.Callback}) by calling
-{@link android.view.SurfaceHolder#addCallback(SurfaceHolder.Callback) addCallback()}
-(pass it this). Then override each of the
-{@link android.view.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 {@link android.view.SurfaceHolder#lockCanvas() 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
-{@link android.view.SurfaceHolder#unlockCanvasAndPost(Canvas) unlockCanvasAndPost()}, passing it
-your Canvas object. The Surface will now draw 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 {@link android.graphics.Canvas#drawColor(int) drawColor()} or setting a background image
-with {@link android.graphics.Canvas#drawBitmap(Bitmap,Rect,RectF,Paint) 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.
docs/ directory of the NDK
+download.- There are two foundational classes in the Android framework that let you create and manipulate +
There are two foundational classes in the Android framework that let you create and manipulate graphics with the OpenGL ES API: {@link android.opengl.GLSurfaceView} and {@link android.opengl.GLSurfaceView.Renderer}. If your goal is to use OpenGL in your Android application, understanding how to implement these classes in an activity should be your first objective. @@ -89,22 +88,22 @@ understanding how to implement these classes in an activity should be your first
The {@link android.opengl.GLSurfaceView.Renderer} interface requires that you implement the following methods:
If you'd like to start building an app with OpenGL right away, have a look at the tutorials for -OpenGL ES 1.0 or +OpenGL ES 1.0 or OpenGL ES 2.0!
If your application uses OpenGL features that are not available on all devices, you must include -these requirements in your AndroidManifest.xml file. Here are the most common OpenGL manifest declarations:
@@ -200,14 +199,14 @@ shown below. compression formats, you must declare the formats your application supports in your manifest file using {@code <supports-gl-texture>}. For more information about available texture compression -formats, see Texture compression support. +formats, see Texture compression support.Declaring texture compression requirements in your manifest hides your application from users with devices that do not support at least one of your declared compression types. For more information on how Android Market filtering works for texture compressions, see the Android Market and texture compression filtering section of the {@code -<supports-gl-texture>} documentation.
+<supports-gl-texture>} documentation. @@ -237,7 +236,7 @@ matrix creates a transformation that renders objects from a specific eye positioIn the ES 1.0 API, you apply projection and camera view by creating each matrix and then adding them to the OpenGL environment.
- +
public void onSurfaceChanged(GL10 gl, int width, int height) {
gl.glViewport(0, 0, width, height);
-
+
// make adjustments for screen ratio
float ratio = (float) width / height;
gl.glMatrixMode(GL10.GL_PROJECTION); // set matrix to projection mode
gl.glLoadIdentity(); // reset the matrix to its default state
gl.glFrustumf(-ratio, ratio, -1, 1, 3, 7); // apply the projection matrix
- }
+ }
In the ES 2.0 API, you apply projection and camera view by first adding a matrix member to the vertex shaders of your graphics objects. With this matrix member added, you can then generate and apply projection and camera viewing matrices to your objects.
- +
- private final String vertexShaderCode =
-
+ private final String vertexShaderCode =
+
// This matrix member variable provides a hook to manipulate
// the coordinates of objects that use this vertex shader
"uniform mat4 uMVPMatrix; \n" +
-
+
"attribute vec4 vPosition; \n" +
"void main(){ \n" +
-
+
// the matrix must be included as part of gl_Position
" gl_Position = uMVPMatrix * vPosition; \n" +
-
+
"} \n";
Note: The example above defines a single transformation matrix @@ -340,7 +339,7 @@ variable defined in the vertex shader above.
public void onDrawFrame(GL10 unused) {
...
// Combine the projection and camera view matrices
Matrix.multiplyMM(mMVPMatrix, 0, mProjMatrix, 0, mVMatrix, 0);
-
+
// Apply the combined projection and camera view transformations
GLES20.glUniformMatrix4fv(muMVPMatrixHandle, 1, false, mMVPMatrix, 0);
-
+
// Draw objects
...
}
@@ -498,7 +497,7 @@ must run this call on several target devices to determine what compression types
supported.
While performance, compatibility, convenience, control and other factors may influence your decision, you should pick an OpenGL API version based on what you think provides the best experience for your users.