欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2022-07-02 12:02:53
实例 相关阅读 了解SurfaceView ......

实例

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