开发者

Simple simple 2D graphics in a view

开发者 https://www.devze.com 2023-01-11 08:40 出处:网络
What is the simplest way to draw pixels, lines and circles on a View? I want to move a cross cursor around, so nothing particularly intensive.

What is the simplest way to draw pixels, lines and circles on a View? I want to move a cross cursor around, so nothing particularly intensive.

I thought I could extend SurfaceView and add it to an XML and it would just work, but it just appears black, however, when I look at the layout view of localmap.xml in eclipse, the graphics appear as expected.

Any ideas? My onDraw is never called on the emulator, and even calling invalidate on the class makes no difference. I shall keep trying but can anyone see anything I've missed? or is there a better way entirely?

  • Frink

localmap.xml contains the following (in a RelativeLayout)

  <com.example.android.game.LocalMapView
android:id="@+id/localmap_map"
android:layout_width="fill_parent"
android:layout_above="@id/localmap_planettext"
android:layout_below="@id/header"/>

LocalMapView.java contains the following (amongst other things)

public class LocalMapView extends SurfaceView {

Paint mPaint = new Paint();

//Construct a LocalMapView based on inflation from XML
public LocalMapView(Context context, AttributeSet attrs) {
    super(context, attrs);

    // allow the map to receive the focus
    setFocusable(true);

}

private void drawPixel(Canvas canvas, int x, int y, int colour) {
    mPaint.setColor(colour);
    if ((x &开发者_运维百科gt;= MAP_MIN_X) && (x < MAP_MAX_X) && (y >= MAP_MIN_Y) && (y < MAP_MAX_Y)) {
        canvas.drawPoint(((float)x * mScaleMapToScreenX), ((float)y * mScaleMapToScreenY), mPaint);
    }
}



private void drawCircle(Canvas canvas, int x, int y, int radius, int colour) {
    mPaint.setColor(colour);
canvas.drawCircle(((float)x), ((float)y), ((float)radius), mPaint);
}




@Override
public void onDraw(Canvas canvas) {
    super.onDraw(canvas);       
    drawCircle(canvas, MAP_MAX_X/2, MAP_MAX_Y/2, 1, 0xFF00FFFF);
    drawPixel(canvas, MAP_MAX_X/2, MAP_MAX_Y/2, 0xFF000000);
}


With SurfaceView you don't do the drawing in onDraw(). You have to grab a canvas from the underlying surface and draw in there. It seems to me you don't really know why you are using a SurfaceView. Just use a normal View instead and onDraw() will work just fine.

0

精彩评论

暂无评论...
验证码 换一张
取 消