12.26
package com.example.myapp;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class CustomSurfaceView extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder surfaceHolder;
private Paint paint;
private DrawThread drawThread;
public CustomSurfaceView(Context context) {
super(context);
init();
}
private void init() {
surfaceHolder = getHolder();
surfaceHolder.addCallback(this);
paint = new Paint();
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.FILL);
drawThread = new DrawThread();
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
drawThread.setRunning(true);
drawThread.start();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// Respond to surface changes, if needed
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
drawThread.setRunning(false);
while (retry) {
try {
drawThread.join();
retry = false;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private class DrawThread extends Thread {
private boolean running = false;
public void setRunning(boolean running) {
this.running = running;
}
@Override
public void run() {
Canvas canvas;
while (running) {
canvas = null;
try {
canvas = surfaceHolder.lockCanvas(null);
if (canvas != null) {
// Draw on the canvas
canvas.drawColor(Color.WHITE);
canvas.drawRect(100, 100, 200, 200, paint);
}
} finally {
if (canvas != null) {
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.myapp.CustomSurfaceView
android:id="@+id/customSurfaceView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
本文来自博客园,作者:赵千万,转载请注明原文链接:https://www.cnblogs.com/zhaoqianwan/p/18602767
千万千万赵千万