2016-09-19 70 views
1

如何在不使用图像的情况下在libgdx中创建简单的圆角矩形按钮?该按钮应该有一个阴影,并应处理按下状态。我希望它是编程方式,以便稍后更改颜色,样式等。如何在libgdx中创建一个简单的圆角矩形按钮?

+0

你可以具体说明你的意思吗?你可以在屏幕上看到的所有东西都是一个“图像”。你在具体试图避免什么,为什么? – Tenfour04

回答

1

我对您的问题的理解是如何在程序内创建一个圆角矩形,而无需在代码之外预先生成任何图像。

我前段时间处于类似的情况,并且结束写下面的函数,该函数根据参数(所有单位都以像素为单位)生成一个圆角矩形Pixmap。它也适用于不同的alpha值以允许不透明度(这就是为什么使用两个对象Pixmap)。

如果您发现使用更易于渲染,则可以轻松地将得到的Pixmap传递给Texture的构造函数。

public static Pixmap createRoundedRectangle(int width, int height, int cornerRadius, Color color) { 

     Pixmap pixmap = new Pixmap(width, height, Pixmap.Format.RGBA8888); 
     Pixmap ret = new Pixmap(width, height, Pixmap.Format.RGBA8888); 

     pixmap.setColor(color); 

     pixmap.fillCircle(cornerRadius, cornerRadius, cornerRadius); 
     pixmap.fillCircle(width - cornerRadius - 1, cornerRadius, cornerRadius); 
     pixmap.fillCircle(cornerRadius, height - cornerRadius - 1, cornerRadius); 
     pixmap.fillCircle(width - cornerRadius - 1, height - cornerRadius - 1, cornerRadius); 

     pixmap.fillRectangle(cornerRadius, 0, width - cornerRadius * 2, height); 
     pixmap.fillRectangle(0, cornerRadius, width, height - cornerRadius * 2); 

     ret.setColor(color); 
     for (int x = 0; x < width; x++) { 
      for (int y = 0; y < height; y++) { 
       if (pixmap.getPixel(x, y) != 0) ret.drawPixel(x, y); 
      } 
     } 
     pixmap.dispose(); 

     return ret; 
    } 

使用此功能,它应该不会太困难,使自己的包装对象(例如RoundedRectangle)每一个参数被改变,需要进行渲染的时间,这将重新绘制图像。

+0

谢谢,但我想这种方法不是很高效...... – user1615898

+0

它做O(宽*高)操作相当快(但不是在你的循环中),但你不需要每帧重新渲染图像,而只有当任何值被改变时。 –