繁体   English   中英

渲染不规则按钮形状-最佳做法

[英]Rendering irregular button shapes - best practice

我正在尝试创建一个具有相当复杂的UI的应用程序。 我试图了解什么是在屏幕上呈现不规则按钮形状的最佳实践。

我添加此图像作为示例。 这些木板中的每一个都是一个按钮。 我显然不能使用Android的Button或ImageButton,因为形状不是矩形。

我假设我需要将其直接绘制到画布上或使用onDraw或Draw来实现。 这是我应该用来将它们呈现为按钮的正确方法吗? 高度赞赏其中的任何良好阅读材料。

谢谢

在此处输入图片说明

您可以通过以下方式创建自定义视图:

  1. onDraw()绘制3个位图,每个位图代表一个按钮(其他两个按钮是透明的),
  2. onTouch()对照这些位图检查触摸的像素,以查看单击了哪个位图

程式码片段:

public class DrawingBoard extends View {

    Bitmap mBitmap1 = BitmapFactory.decodeResource(getResources(), R.drawable.button1);
    Bitmap mBitmap2 = BitmapFactory.decodeResource(getResources(), R.drawable.button2);
    Bitmap mBitmap3 = BitmapFactory.decodeResource(getResources(), R.drawable.button3);

    public DrawingBoard (Context context) {
        // TODO Auto-generated constructor stub
        super (context);            
    }
    @Override
    protected void onDraw (Canvas canvas) {
        canvas.drawBitmap(mBitmap1, 0, 0, null);
        canvas.drawBitmap(mBitmap2, 0, 0, null);
        canvas.drawBitmap(mBitmap3, 0, 0, null);
    }
    @Override
    public boolean onTouchEvent (MotionEvent event) {

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN : 
                int xx = (int)event.getX();
                int yy = (int)event.getY();
                if(Color.alpha(mBitmap1.getPixel(xx,yy)) != 0) {
                    // button1 pressed
                }
                else if(Color.alpha(mBitmap2.getPixel(xx,yy)) != 0) {
                    // button2 pressed
                }
                else if(Color.alpha(mBitmap3.getPixel(xx,yy)) != 0) {
                    // button3 pressed
                }
                break;
        }

        return true;

    }
@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) 
    {
     // bitmaps are assumed to be of the same size
     setMeasuredDimension(mBitmap1.getWidth(),mBitmap1.getHeight());
    }    
}

我没有测试代码,它可能有错误。

一种变体-您可以创建一个虚拟位图,用于存储整个图像上像素的“匹配代码”。 您可以从原始图片创建图片,但用ID替换像素以检测触摸了哪个区域,所有其他像素为“空”(0x0)。 因此getPixel()将返回按钮的ID。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM