Android SurfaceView简例
Android中各的SurfaceView和View有很大的不同,两者应用场景不同。大多数View能做的事情SurfaceView也可以,但是SurfaceView效率更高。Android的View绘制过程由Android系统控制,刷新机制开发者比较难以控制。而SurfaceView支持高频、多线程绘制。SurfaceView不存在是否在Android UI主线程绘制问题。通常SurfaceView用于游戏、多媒体(视频)开发。
现在给出一个例子。
写一个自定义的SurfaceView,MySurfaceView.java:
package zhangphil.view;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
/**
* Created by Phil on 2017/9/12.
*/
public class MySurfaceView extends SurfaceView {
public MySurfaceView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
SurfaceHolder holder = getHolder();
final MyTask task = new MyTask(holder);
holder.addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
task.startTask();
}
@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
task.stopTask();
}
});
}
private class MyTask extends Thread {
private int width;
private int height;
private SurfaceHolder surfaceHolder;
private Paint paint;
private float radius = 0;
public boolean stopTask = false;
public MyTask(SurfaceHolder surfaceHolder) {
this.surfaceHolder = surfaceHolder;
paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(10f);
}
public void startTask() {
stopTask = false;
this.start();
}
public void stopTask() {
stopTask = true;
}
@Override
public void run() {
while (!stopTask) {
try {
Thread.sleep(1);
} catch (Exception e) {
e.printStackTrace();
}
Canvas canvas = surfaceHolder.lockCanvas();
width = getWidth();
height = getHeight();
canvas.drawColor(Color.WHITE);
canvas.drawCircle(width / 2, height / 2, radius++, paint);
surfaceHolder.unlockCanvasAndPost(canvas);
//如果半径大于边界,置0.
if (radius >= (width / 2)) {
radius = 0;
}
}
}
}
}
测试的activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/holo_blue_light"
tools:context="zhangphil.view.MainActivity">
<zhangphil.view.MySurfaceView
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_centerInParent="true" />
</RelativeLayout>
代码运行结果: