您当前的位置: 首页 >  android

命运之手

暂无认证

  • 1浏览

    0关注

    747博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

【Android】【绘图】SurfaceView使用示例

命运之手 发布时间:2019-01-26 10:25:31 ,浏览量:1

以下代码实现一个绘制正弦波的SurfaceView

public class SinWaveSurfaceView extends SurfaceView implements SurfaceHolder.Callback, Runnable {

    private SurfaceHolder holder;
    private Paint paint;
    private boolean isDrawing;

    private Path path;

    private double x;
    private double y;

    private int screenWidth;

    public SinWaveSurfaceView(Context context) {
        this(context, null, 0);
    }

    public SinWaveSurfaceView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SinWaveSurfaceView(Context context, AttributeSet attrSet, int style) {
        super(context, attrSet, style);
        init(context, attrSet);
    }

    private void init(Context context, AttributeSet attrSet) {
        holder = getHolder();
        holder.addCallback(this);
        paint = new Paint();
        paint.setColor(ColorUtil.LIGHT_BLUE);
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.FILL_AND_STROKE);
        paint.setStrokeWidth(10);
        path = new Path();
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        isDrawing = true;
        path.moveTo(0, 800);
        path.moveTo(0, 0);
        screenWidth = DeviceUtil.getScreenSize(getContext()).w;
        new Thread(this).start();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        isDrawing = false;
    }

    private void draw() {
        long start = TimeUtil.timestamp();
        Canvas canvas = holder.lockCanvas();
        if (x > screenWidth)
            canvas.translate((float) (screenWidth - x), MathUtil.randomInt(-1, 1));
        canvas.drawColor(ColorUtil.BLACK_80);
        canvas.drawPath(path, paint);
        holder.unlockCanvasAndPost(canvas);
        long end = TimeUtil.timestamp();
        //绘制一帧的时间
        CodeUtil.log(end - start);
    }

    @Override
    public void run() {
        while (isDrawing) {
            ++x;
            y = 100 * Math.sin(2 * Math.PI * x / 200) + 800;
            path.lineTo((int) x, (int) y);
            draw();
        }
    }
}
关注
打赏
1654938663
查看更多评论
立即登录/注册

微信扫码登录

0.0648s