SurfaceView高性能绘制(五)代码实践篇-让绘制的图片运动

版权声明:本文为博主原创文章,不得随意转载,转载请注明出处!!! https://blog.csdn.net/YuDBL/article/details/87877026

一、前言

上篇文章写了关于绘制多张图片的文章 SurfaceView高性能绘制(四)代码实践篇-绘制多张图片,这篇文章将讲讲让绘制的图片运动,那么我们如何让我们的图片运动呢?肯定是改变x、y轴的坐标

二、主要代码说明

在绘制线程DrawingThread,我们添加如下代码:

                for(DrawingItem item : locations){//循环绘图

                    //思考:我们如何让我们的图片运动?改变x、y轴的坐标。相关属性:绘制屏幕的宽度、图片宽度、图片的坐标

                    // 横坐标超出绘制屏幕,更新横坐标位置
                    item.x += (item.isHorizontal? 5 : -5);
                    //this.drawingWidth-iconBitmap.getWidth() 其实就是图片横坐标的运动范围
                    if (item.x>= this.drawingWidth-iconBitmap.getWidth()){
                        item.isHorizontal = false;
                    }else {
                        item.isHorizontal = true;
                    }

                    // 纵坐标超出绘制屏幕,更新纵坐标位置
                    item.y += (item.isVertical? 12 : -12);
                    if(item.y>= this.drawingHeight- iconBitmap.getHeight()){
                        item.isVertical = false;
                    }else {
                        item.isVertical = true;
                    }

                    //绘图
                    lockCanvas.drawBitmap(iconBitmap, item.x, item.y, paint);

                }

我们如何让我们的图片运动?改变x、y轴的坐标。那么它主要是对绘制屏幕的宽度、图片宽度、图片的坐标 进行操作。

那么如何得到绘制屏幕的宽高?我们首先声明属性、定义方法

 private int drawingWidth,drawingHeight;//定义SurfaceView的宽高(绘制的方向、范围)
   
 public void updateSize(int width, int height){
        this.drawingWidth = width;
        this.drawingHeight = height;
    }

然后在自定义的SurfaceView类MySurfaceView里面获取传递

    @Override
//    public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
//AS没有导入源码,所以参数杂乱
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        //改变---例如:SurfaceView宽度、高度发生了改变
        this.drawingThread.updateSize(width,height);
    }

三、效果图、源码

(1)效果图

(2)源码

https://download.csdn.net/download/yudbl/10970750

相关链接:

Exception dispatching input event,Exception in MessageQueue callback: handleReceiveCallback,空指针

https://blog.csdn.net/antimage08/article/details/50411595

猜你喜欢

转载自blog.csdn.net/YuDBL/article/details/87877026