您可以在您的活动中声明一个内部类,以便参考以下代码:
public class GraphicsTest extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new GraphicsTestView(this));
}
private static class GraphicsTestView extends View
{
private ShapeDrawable mDrawable =
new ShapeDrawable();
/* Drawable's are objects which can be drawn on a Canvas
ShapeDrawable is used to draw primitive shapes such as:
ArcShape, OvalShape, PathShape, RectShape, RoundRectShape
A Canvas is the object provided by Android on which
a view tries to draw itself. In addition to ShapeDrawable,
there are other subclasses of Drawable like PictureDrawable,
RotateDrawable, ScaleDrawable, ClipDrawable,GradientDrawable, etc
Some of these we will see when we consider the XML approach to
graphics
*/
public GraphicsTestView (Context context)
{
super(context);
setFocusable(true);
this.mDrawable.getPaint().setColor(0xFFFF0000);
//argb where a is alpha (transparency)
}
@Override
protected void onDraw(Canvas canvas)
/* the onDraw method is where a view draws itself
this is our first time overriding it.
*/
{
int x = 10;
int y = 10;
int width = 300;
int height = 50;
this.mDrawable.setBounds(x, y, x + width, y + height);
this.mDrawable.draw(canvas);
ArcShape arc = new ArcShape(45,90); //start angle, sweep angle
ShapeDrawable test = new ShapeDrawable(arc);
Paint p = test.getPaint();
p.setColor(0xFF00FFFF);
p.setStyle(Paint.Style.STROKE);
test.setBounds(10, 70, 310, 370);
//Top-Left, Bottom Right of rectangle to draw into
test.draw(canvas);
}
}
}