Tải bản đầy đủ (.pdf) (104 trang)

Graphic 2D 3D with OpenGL

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (820.85 KB, 104 trang )

안드로이드 애플리케이션 교육 자료 – 7
Graphics, 2D and 3D with OpenGL
www.kandroid.org 관리자 : 양정수 (), 닉네임:들풀
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=" />xmlns:kandroid=" />android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent”
>
<org.kandroid.testApp.CustomView
android:background="@drawable/red"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
kandroid:text="Red"/>
<org.kandroid.testApp.CustomView
android:background="@drawable/blue"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
kandroid:text="Blue" kandroid:textSize="20dp"/>
<org.kandroid.testApp.CustomView
android:background="@drawable
/
green"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
kandroid:text="Green" kandroid:textColor="#ffffffff" />
/Li L
2Korea Android Community- www.kandroid.org
<
/Li
near
L


ayout>
public class MyView extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
public class CustomView extends View {
public CustomView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public CustomView(Context context,
A
ttributeSet attrs) {
super(context, attrs);
}
public CustomView(Context context) {
super(context);
}
}
3Korea Android Community- www.kandroid.org
4Korea Android Community- www.kandroid.org
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(measureWidth(widthMeasureSpec),
measureHeight
(
heightMeasureSpec
));

measureHeight
(
heightMeasureSpec
));
}
private int measureHeight(int measureSpec) {
int result = 0;
int
specMode
=
MeasureSpec getMode
(
measureSpec
);
int
specMode
=

MeasureSpec
.
getMode
(
measureSpec
);
int specSize = MeasureSpec.getSize(measureSpec);
mAscent = (int) mTextPaint.ascent();
if (specMode == MeasureSpec.EXACTLY) {
result =
specSize
;

result

=

specSize
;
} else {
result = (int) (-mAscent + mTextPaint.descent()) + getPaddingTop() + getPaddingBottom();
if (specMode == MeasureSpec.AT_MOST) {
result = Math min(result
specSize
);
result

=

Math
.
min(result
,
specSize
);
}
}
return result;
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);

canvas drawText
(
mText
getPaddingLeft
()
getPaddingTop
()
mAscent
mTextPaint
);
5Korea Android Community- www.kandroid.org
canvas
.
drawText
(
mText
,
getPaddingLeft
()
,
getPaddingTop
()
-
mAscent
,
mTextPaint
);
}
6Korea Android Community- www.kandroid.org
<?xml version="1.0" encoding="WINDOWS-1252" standalone="no"?>

<jardesc>
<j th "D /D l t/P j t /A d id/M Vi j "/>
<j
ar pa
th
=
"D
:
/D
eve
l
opmen
t/P
ro
j
ec
t
s
/A
n
d
ro
id/M
y
Vi
ew.
j
ar
"/>
<options buildIfNeeded="true" compress="true" descriptionLocation="/MyView/MyView.jardesc“

exportErrors="false" exportWarnings="true" includeDirectoryEntries="false" overwrite="false“
saveDescription="true" storeRefactorings="false" useSourceFolders="false"/>
<
tdRfti
dtiIf
"t "
ttlOl
"f l "/>
<
s
t
ore
dR
e
f
ac
t
or
i
ngs
d
epreca
ti
on
I
n
f
o=
"t
rue

"
s
t
ruc
t
ura
lO
n
l
y=
"f
a
l
se
"/>
<selectedProjects/>
<manifest generateManifest="true" manifestLocation="" manifestVersion="1.0"
reuseManifest="false" saveManifest="false" usesManifest="true">
<sealing
sealJar
"false">
<sealing

sealJar
=
"false">
<packagesToSeal/>
<packagesToUnSeal/>
</sealing>
</manifest>

</manifest>
<selectedElements exportClassFiles="true" exportJavaFiles="true" exportOutputFolder="false">
<javaElement handleIdentifier="=MyView/src&lt;org.kandroid.testApp{MyView.java"/>
<javaElement handleIdentifier="=MyView/src&lt;org.kandroid.testApp{CustomView.java"/>
<
javaElement
handleIdentifier
="=
MyView
/
src&lt;org kandroid testApp
{R java"/>
<
javaElement
handleIdentifier
="=
MyView
/
src&lt;org
.
kandroid
.
testApp
{R
.
java"/>
</selectedElements>
<fatjar builder="org.eclipse.jdt.ui.plain_jar_builder" launchConfig=""/>
</jardesc>
7Korea Android Community- www.kandroid.org

External Library 사용
8Korea Android Community- www.kandroid.org
9Korea Android Community- www.kandroid.org
1. Graphics
2. 2D Gra
p
hics
p
3. 3D with OpenGL
3.

3D

with

OpenGL
Graphics
Overview
Android graphics are powered by a custom 2D graphics library and OpenGL ES 1.0 for high
performance 3D graphics. The most common 2D graphics APIs can be found in the drawable
package. OpenGL APIs are available from the Khronos OpenGL ES package, plus some Android
O GL tiliti
O
pen
GL
u
tiliti
es.
When starting a project, it's important to consider exactly what your graphical demands will be.
Varying graphical tasks are best accomplished with varying techniques. For example, graphics

d i ti f th t ti li ti h ld b i l t d h diff tl th
an
d
an
i
ma
ti
ons
f
or a ra
th
er s
t
a
ti
c app
li
ca
ti
on s
h
ou
ld

b
e
i
mp
l
emen

t
e
d
muc
h

diff
eren
tl
y
th
an
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 the 're best s ited for
tasks

the
y
're

best

s
u
ited

for
.
If you're specifically looking for information on drawing 3D graphics, this page won't help a lot.

However, the information below, on Drawing 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
will

give

you

a

quick

idea

of

how

you

should

draw

to

the

View


hierarchy
.
For

more

information

on

Android's 3D graphic utilities (provided by the OpenGL ES API), read 3D with OpenGL and refer
to other OpenGL documentation.
11Korea Android Community- www.kandroid.org
Graphics
Consider your options
When drawing 2D graphics, you'll typically do so in one of two ways:
a. Draw your graphics or animations into a View object from your layout. In this manner, the
drawing (and any animation) of your graphics is handled by the system's normal View hierarchy
drawing process - you simply define the graphics to go inside the View.
b. Draw your graphics directly to a Canvas. This way, you personally call the appropriate class's
draw() method (passing it your Canvas), or one of the Canvas draw () methods (like
drawPicture()). In doing so, you are also in control of any animation.
Option "a," drawing to a View, is your best choice when you want to draw simple graphics that do
not need to change dynamically and are not part of a performance-intensive game. For example,
you should draw your graphics into a View when you want to display a static graphic or predefined
animation, within an otherwise static application. Read Simple Graphics Inside a View.
Option "b," drawing to a Canvas, is better when you're application needs to regularly re-draw itself.
Basically, any video game should be drawing to the Canvas on its own. However, there's more than
one way to do this:
• In the same thread as your UI Activity, wherein you create a custom View component in your layout,

call invalidate() and then handle the onDraw() callback
12Korea Android Community- www.kandroid.org
• 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()).
Graphics
Simple Graphics Inside a View
If you'll be drawing some simple graphics (images, shapes, colors, pre-defined animations, etc.),
then you should probably just draw to the background of a View or to the content of an ImageView in
your layout.
In this case, you can skip the rest of this document and learn how to draw graphics and animations in
the 2D Graphics document.
13Korea Android Community- www.kandroid.org
Graphics
Draw with a Canvas
When you're writing an application in which you would like to perform specialized drawing and/or
control the animation of graphics, you should do so by drawing through a Canvas.
A Canvas works for you as a pretense, or interface, to the actual surface upon which your
graphics will be drawn - it holds all of your "draw" calls. Via the Canvas, your drawing is actually
performed upon an underlying Bitmap, which is placed into the window.
In the event that you're drawing within the onDraw() callback method, the Canvas is provided for you
and you need only place your drawing calls upon it. You can also acquire a Canvas from
SurfaceHolder.lockCanvas(), when dealing with a SurfaceView object. (Both of these scenarios are
discussed in the following sections.)
However, if you need to create a new Canvas, then you must define the Bitmap upon which drawing
will actually be performed. The Bitmap is always required for a Canvas. You can set up a new Canvas
like this:
Bitmap b = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
14Korea Android Community- www.kandroid.org
Graphics

Draw with a Canvas
Now your Canvas will draw onto the defined Bitmap. After drawing upon it with the Canvas, you can
then carry your Bitmap to another Canvas with one of the Canvas.drawBitmap(Bitmap, ) methods.
It's recommended that you ultimately draw your final graphics through a Canvas offered to you by
View.onDraw() or SurfaceHolder.lockCanvas() (see the following sections).
The Canvas class has its own set of drawing methods that you can use, like drawBitmap( ),
drawRect( ), drawText( ), and many more. Other classes that you might use also have draw()
methods. For example, you'll probably have some Drawable objects that you want to put on the
Canvas. Drawable has its own draw() method that takes your Canvas as an arguement.
15Korea Android Community- www.kandroid.org
Graphics
Draw with a Canvas / On a View
If you're application does not require a significant amount of processing or frame-rate speed (perhaps
for a chess game, a snake game, or another slowly-animated application), then you should consider
creating a custom View component and drawing with a Canvas in View.onDraw().
The most convenient aspect of doing so is that the Android framework will provide you with a pre-
defined Canvas to which you will place your drawing calls.
To start, extend the View class (or descendent thereof) and define the onDraw() callback method. This
method will be called by the Android framework to request that your View draw itself. This is where
you will perform all your calls to draw through the Canvas, which is passed to you through the
onDraw() callback.
16Korea Android Community- www.kandroid.org
Graphics
Draw with a Canvas / On a View (cont.)
The Android framework will only call onDraw() as necessary. Each time that your application is
prepared to be drawn, you must request your View be invalidated by calling invalidate(). This indicates
that you'd like your View to be drawn and Android will then call your onDraw() method (though is not
guaranteed that the callback will be instantaneous).
Inside your View component's onDraw(), use the Canvas given to you for all your drawing, using
various Canvas.draw () methods, or other class draw() methods that take your Canvas as an

argument. Once your onDraw() is complete, the Android framework will use your Canvas to draw a
Bitmap handled by the system.
Note: In order to request an invalidate from a thread other than your main Activity's thread, you must
call postInvalidate().
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/.
17Korea Android Community- www.kandroid.org
Graphics
Draw with a Canvas / On a SurfaceView
The SurfaceView is a special subclass of View that offers a dedicated drawing surface within the
View hierarchy.
The aim is to offer this drawing surface to an application's secondary thread, so that the application
isn't required to wait until the system's View hierarchy is ready to draw.
Instead, a secondary thread that has reference to a SurfaceView can draw to its own Canvas at its
own pace.
To begin, you need to create a new class that extends SurfaceView.
The class should also implement SurfaceHolder.Callback.
This subclass is an interface that will notify you with information about the underlying Surface, such as
when it is created, changed, or destroyed.
These events are important so that you know when you can start drawing, whether you need to make
adjustments based on new surface properties, and when to stop drawing and potentially kill some
tasks.
Inside your SurfaceView class is also a good place to define your secondary Thread class, which will
perform all the drawing procedures to your Canvas.
18Korea Android Community- www.kandroid.org
Graphics
Draw with a Canvas / On a SurfaceView (cont.)

Instead of handling the Surface object directly, you should handle it via a SurfaceHolder.
So, when your SurfaceView is initialized, get the SurfaceHolder by calling getHolder(). You should
then notify the SurfaceHolder that you'd like to receive SurfaceHolder callbacks (from
SurfaceHolder.Callback) by calling addCallback() (pass it this). Then override each of the
SurfaceHolder.Callback methods inside your SurfaceView class.
In order to draw to the Surface Canvas from within your second thread, you must pass the thread your
SurfaceHandler and retrieve the Canvas with lockCanvas(). You can now take the Canvas given to
you by the SurfaceHolder and do your necessary drawing upon it. Once you're done drawing with the
Canvas, call unlockCanvasAndPost(), passing it your Canvas object. The Surface will now draw the
Canvas as you left it.
Perform this sequence of locking and unlocking the canvas each time you want to redraw.
Note: On each pass you retrieve the Canvas from the SurfaceHolder, the previous state of the Canvas
will be retained. In order to properly animate your graphics, you must re-paint the entire surface. For
example, you can clear the previous state of the Canvas by filling in a color with drawColor() or setting
a background image with drawBitmap(). Otherwise, you will see traces of the drawings you previously
performed.
For a sample application, see the Lunar Landar game, in the SDK samples folder: <your-sdk-
19Korea Android Community- www.kandroid.org
directory>/samples/LunarLander
/
. Or, browse the source in the Sample Code section.
1. Graphics
2. 2D Gra
p
hics
p
3. 3D with OpenGL
3.

3D


with

OpenGL
2D Graphics
Overview
Android offers a custom 2D graphics library for drawing and animating shapes and images. The
android.graphics.drawable and android.view.animation packages are where you'll find the common
classes used for drawing and animating in two-dimensions.
This document offers an introduction to drawing graphics in your Android application. We'll discuss the
basics of using Drawable objects to draw graphics, how to use a couple subclasses of the Drawable
class, and how to create animations that either tween (move, stretch, rotate) a single graphic or
animate a series of graphics (like a roll of film).
21Korea Android Community- www.kandroid.org
2D Graphics
Drawables
A Drawable is a general abstraction for "something that can be drawn." You'll discover that the
Drawable class extends to define a variety of specific kinds of drawable graphics, including
BitmapDrawable, ShapeDrawable, PictureDrawable, LayerDrawable, and several more. Of course,
you can also extend these to define your own custom Drawable objects that behave in unique ways.
There are three ways to define and instantiate a Drawable:
1. using an image saved in your project resouces;
2. using an XML file that defines the Drawable properties; or
3. using the normal class constructors.
Below, we'll discuss each the first two techniques (using constructors is nothing new for an
experienced developer).
22Korea Android Community- www.kandroid.org
2D Graphics
Drawables / Creating from resource images
A simple way to add graphics to your application is by referencing an image file from your project

resources. Supported file types are PNG (preferred), JPG (acceptable) and GIF (discouraged). This
technique would obviously be preferred for application icons, logos, or other graphics such as those
used in a game.
To use an image resource, just add your file to the res/drawable/ directory of your project. From there,
you can reference it from your code or your XML layout. Either way, it is referred using a resource ID,
which is the file name without the file type extension (E.g., my_image.png is referenced as my_image).
Example code
The following code snippet demonstrates how to build an ImageView that uses an image from
drawable resources and add it to the layout.
23Korea Android Community- www.kandroid.org
2D Graphics
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_CONTEN
T
,
LayoutParams.WRAP_CONTENT));
// Add the ImageView to the layout and set the layout as the content view
mLinearLayout.addView(i);
setContentView(mLinearLayout);
}
24Korea Android Community- www.kandroid.org
}

2D Graphics
25Korea Android Community- www.kandroid.org

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×