当前位置: 移动技术网 > 移动技术>移动开发>Android > Android SurfaceView实现跟随手指移动的光标

Android SurfaceView实现跟随手指移动的光标

2018年08月18日  | 移动技术网移动技术  | 我要评论

实例

public class dragsurfaceview extends surfaceview implements surfaceholder.callback,runnable{
    private int screenw;        //屏幕宽度
    private int screenh;        //屏幕高度
    private float cx = 100;      //默认x坐标
    private float cy = 100;      //默认y坐标
    private bitmap mbitmap;
    private surfaceholder msurfaceholder = null;
    private thread thread = null;
    public dragsurfaceview(context context,@nullable attributeset attrs) {
        super(context,attrs);
        msurfaceholder = getholder();
        msurfaceholder.addcallback(this);
        mbitmap=getbitmapresources(context,r.drawable.x1);
        thread=new thread(this);

    }
    public static bitmap getbitmapresources(context context,int resid){
         return bitmapfactory.decoderesource(context.getresources(),resid);
   }

    protected void mydraw() {
        //获取canvas实例
        canvas canvas = msurfaceholder.lockcanvas();
        //将屏幕设置为白色
        canvas.drawcolor(color.white);
        //绘制图片和位置
        canvas.drawbitmap(mbitmap,cx,cy,null);
        //将画好的画布提交
        msurfaceholder.unlockcanvasandpost(canvas);
    }

    @override
    public void run() {
        while(true){
            try{
                mydraw();
                thread.sleep(100);
            }catch(interruptedexception e){
                e.printstacktrace();
            }
        }
    }

    @suppresslint("clickableviewaccessibility")
    @override
    public boolean ontouchevent(motionevent event) {
        switch (event.getaction()) {
            case motionevent.action_down:
                // 按下
                cx = (int) event.getx();
                cy = (int) event.gety();
                break;
            case motionevent.action_move:
                // 移动
                cx = (int) event.getx();
                cy = (int) event.gety();
                break;
            case motionevent.action_up:
                // 抬起
                cx = (int) event.getx();
                cy = (int) event.gety();
                break;
        }
        return true;
    }

    //surface创建的时候调用
    @override
    public void surfacecreated(surfaceholder surfaceholder) {
        //获取屏幕高度
        screenw = getwidth();
        screenh = getheight();
        thread.start();
    }

    //surface被改变的时候调用
    @override
    public void surfacechanged(surfaceholder surfaceholder, int i, int i1, int i2) {

    }

    //surface销毁的时候调用
    @override
    public void surfacedestroyed(surfaceholder surfaceholder) {
        dorecycledifnot(mbitmap);
    }

    //回收一个未被回收的bitmap
    public static void dorecycledifnot(bitmap bitmap) {
        if (!bitmap.isrecycled()) {
            bitmap.recycle();
        }
    }
}

 相关阅读

了解surfaceview

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网