SurfaceView 试用
Posted 小威少威
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SurfaceView 试用相关的知识,希望对你有一定的参考价值。
由于项目需要用到动画效果,如果大量绘制animation,则性能不佳,上网搜了,有surfaceview这个东西(不占用主线程)。因此自己学习了一下,以下demo是实现每个一秒钟绘制显示不同颜色的笑脸。
涉及点:SurfaceView、SurfaceHolder。
一、实现效果:
二、自定义surfaceview类
1、:
继承SurfaceView,实现SurfaceHolder Callback接口。
2、重写构造方法
3、实现三个callback方法:
@Override
public void surfaceCreated(SurfaceHolder holder)
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
@Override
public void surfaceDestroyed(SurfaceHolder holder)
三、整体代码:
public class MySurfaceViewTest extends SurfaceView implements SurfaceHolder.Callback
private SurfaceHolder mSurfaceHolder;
private MyThread mMyThread;
private boolean isDraw = false;
public MySurfaceViewTest(Context context)
super(context);
mSurfaceHolder = this.getHolder();
mSurfaceHolder.addCallback(this);
mMyThread = new MyThread();
private class MyThread extends Thread
@Override
public void run()
while (isDraw)
try
sleep(1000);//睡一秒钟
drawUI();
catch (Exception e)
super.run();
private void drawUI()
Canvas canvas = null;
try
canvas = mSurfaceHolder.lockCanvas();
synchronized (mSurfaceHolder)
drawCanvas(canvas);
finally
if (canvas != null)
mSurfaceHolder.unlockCanvasAndPost(canvas);
private void drawCanvas(Canvas canvas)
// 在 canvas 上绘制需要的图形
if (canvas != null)
Log.d("weiwei","come-----------------------------------------------");
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR); // 清空界面
Paint p = new Paint();
p.setColor(CircleTextImageUtil.getRandomColor());// 设置随机颜色
// //画笑脸弧线
p.setStyle(Paint.Style.STROKE);//设置空心
RectF oval1=new RectF(150,20,180,40);
canvas.drawArc(oval1, 180, 180, false, p);//小弧形
oval1.set(190, 20, 220, 40);
canvas.drawArc(oval1, 180, 180, false, p);//小弧形
oval1.set(160, 30, 210, 60);
canvas.drawArc(oval1, 0, 180, false, p);//小弧形
static class CircleTextImageUtil
/**
* Get the random color.
*
* @return
*/
private static int getRandomColor()
List<Integer> colorList = new ArrayList<Integer>();
colorList.add(Color.RED);
colorList.add(Color.BLUE);
colorList.add(Color.GREEN);
colorList.add(Color.WHITE);
colorList.add(Color.YELLOW);
colorList.add(Color.GRAY);
return colorList.get((int) (Math.random() * colorList.size()));
@Override
public void surfaceCreated(SurfaceHolder holder)
isDraw = true;
mMyThread.start();
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
@Override
public void surfaceDestroyed(SurfaceHolder holder)
isDraw = false;
引用:
public class MainActivity extends AppCompatActivity
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
CrashReport.initCrashReport(getApplicationContext(), "077d3ebb59", false);
MySurfaceViewTest mySurfaceViewTest = new MySurfaceViewTest(this);
// setContentView(R.layout.activity_main);
setContentView(mySurfaceViewTest);
以上是关于SurfaceView 试用的主要内容,如果未能解决你的问题,请参考以下文章