I want to create simple Android application which will draw circles in place where I touch the screen. It is working with View (slowly), but with SurfaceView not. The result is strange - when clicking, whole image is moving. I also tried to call drawing function from another thread, but results are the same. Also found another example with this strange behavior: http://android-er.blogspot.com/2010/05/android-surfaceview.html I work with Android 2.3.3, API level 10. Any help would be appreciated.
package com.samsung.sketchbook;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class SketchBook extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
BookView bookView = new BookView(this);
setContentView(boo开发者_运维知识库kView);
}
class BookView extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder holder;
private Paint paint = new Paint();
private float x, y;
public BookView(Context context) {
super(context);
holder = getHolder();
holder.addCallback(this);
paint.setColor(Color.WHITE);
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
public void surfaceCreated(SurfaceHolder holder) {
Log.d("BookView", "surfaceCreated!");
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
@Override
public boolean onTouchEvent(MotionEvent motionEvent) {
x = motionEvent.getX();
y = motionEvent.getY();
Canvas canvas = holder.lockCanvas(null);
canvas.drawCircle(x, y, 3, paint);
holder.unlockCanvasAndPost(canvas);
return true;
}
}
}
I can recommend you don't use SurfaceView
.
My experience say that it isn't a better solution than View
. Yes, implementation class which extends on View
is slowly, but only when you don't know how to effectively use invalidate()
.
I mean don't use invalidate()
(which draws all canvas), but invalidate(dirtyRect)
(You define the rectangular which you want to redraw, and the rest of the canvas stays just like before) it's very fast.
精彩评论