Android:How to add a button in surface view

前端 未结 4 1970
时光取名叫无心
时光取名叫无心 2020-12-04 14:56

I\'m drawing some graphics and i would like to add a couple of buttons to it. But with the surface view how do we add these buttons programatically ?

4条回答
  •  无人及你
    2020-12-04 15:15

    Make your own button:

    import android.graphics.Bitmap;
    import android.graphics.Canvas;
    import android.graphics.Matrix;
    import android.graphics.RectF;
    
        public class GButton
        {
            public Matrix btn_matrix = new Matrix();
    
            public RectF btn_rect;
    
            float width;
            float height;   
            Bitmap bg;
    
            public GButton(float width, float height, Bitmap bg)
            {
                this.width = width;
                this.height = height;
                this.bg = bg;
    
                btn_rect = new RectF(0, 0, width, height);
            }
    
            public void setPosition(float x, float y)
            {
                btn_matrix.setTranslate(x, y);
                btn_matrix.mapRect(btn_rect);
            }
    
            public void draw(Canvas canvas)
            {
                canvas.drawBitmap(bg, btn_matrix, null);
            }
        }
    

    on touch event:

    float x = ev.getX();
    float y = ev.getY();
    if (my_button.btn_rect.contains(x, y))
    {
        // handle on touch here
    }
    

    alternatively, even better, if you want to also rotate the button it will not be axis-aligned, then use the invert matrix, instead of mapRect map the touch points x,y:

    float pts[] = {x, y};            
    my_button.invert_matrix.mapPoints(pts);           
    if (my_button.btn_rect.contains(pts[0], pts[1])
    {
        // handle on touch here
    }
    

提交回复
热议问题