Um dia destes precisei fazer um monte de botões para um site, um monte mesmo perto de 50, dai minhas mínimas habilidades no Gimp ou no Photoshop me fizeram pensar em outra alternativa … acabei escrevendo código java para resolver o problema: desenhar botões com algum aspecto visual decente !
Se ficaram visualmente agradáveis para todos eu não sei, pelo eu gostei
veja só como ficou bonitinho :

leia mais e veja como isto tudo foi feito
Algumas classes foram criadas:
- ButtonDef – informações sobre o texto do botão e nome da imagem a ser gerada, um para cada botão
- ButtonDefVisual – informações visuais do botão, uma definição é usada para um conjunto de botões, por exemplo: definindo a cor de fundo, tamanho da fonte…
- ColorManager – oferece métodos para clarear e escurecer um cor, criei para fazer as sombras
- FontManager – métodos para centralizar texto, e medidas de uma fonte em um contexto gráfico
- CreateButtonImage – esta cria efetivamente o botão baseado nas definição visuais e definições de botão, usando as classes de cor e fonte
- TestCreateButton – aplicação que chama a criação dos botões
baixe todos os fontes juntos
thz button codigo fonte
Infelizmente não fiz uma interface gráfica para este programa
que quizer usar vai ter que saber um pouco de Java … quem sabe alguém se oferece para fazer a interface …
Vamos dar uma olhada em alguns trechos de código :
a classe TestCreateButton
public class TestCreateButton {
public static void main(String[] args) throws Exception {
ButtonDef button = new ButtonDef("iniciar");
ButtonDefVisual def = new ButtonDefVisual();
// def.setForeground(Color.orange);
def.setForeground(Color.red);
// def.setForeground(new Color(55, 155, 240));
//def.setForeground(new Color(153, 51, 153));
//def.setForeground(new Color(166, 178, 184));
def.setFontColor(Color.yellow);
def.setFontAlpha(100);
ButtonDef [] buttons = {
new ButtonDef("Adicionar ","button_add_address.gif"),
new ButtonDef("Encerrar carrinho"),
new ButtonDef("Continuar compra"),
new ButtonDef("utilizar crédito"),
new ButtonDef("Adicionar ao carrinho")
};
for (int i = 0; i < buttons.length; i++) {
buttons[i].setFileNamePreffix("");
}
CreateButtonImage.createButton( buttons, def);
}
}
Cria uma definição visual e um array de definições de botões que são passados para a classe CreateButtonImage. Observe que a classe ButtonDefVisual possue diversos atributos que podem ser alterados, veja a lista abaixo :
private int width = -1;
private int height = 25;
private Color background = Color.white;
private Color foreground = Color.blue;
private Color fontColor = Color.black;
private int cornerSize = 10;
private int borderLineWidth = 2;
private boolean autoWidth = true;
private int horizontalPadding = 10;
private int fontAlpha = 60;
veja alguns exemplos de resultado (juntei vários botões):
usando def.setForeground(new Color(55, 155, 240));

usando def.setForeground(Color.orange);

usando def.setForeground(Color.red);

usando def.setForeground(new Color(153, 51, 153));

A parte mais imporante do código reside na classe de criação do botão, veja o código a seguir:
public class CreateButtonImage {
/**
* @param setup
* @throws IOException
* @throws FileNotFoundException
* @throws IOException
*/
public static void createButton(ButtonDef b, ButtonDefVisual s)
throws FileNotFoundException, IOException {
BufferedImage buffer = new BufferedImage(s.getWidth(), s.getHeight(),
BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = buffer.createGraphics();
// font definition
Font font = new Font("Tahoma", Font.BOLD, 12);
g2.setFont(font);
int width = s.getWidth();
int height = s.getHeight();
// calculate width
if (s.isAutoWidth()) {
Rectangle2D rect = FontManager.getTextBouds(b.getText(), g2);
width = (int) (rect.getWidth() + (2 * s.getHorizontalPadding()));
buffer = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
g2 = buffer.createGraphics();
g2.setFont(font);
}
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(s.getBackground());
g2.fillRect(0, 0, width, height);
// stroke definition
Stroke stroke = new BasicStroke(s.getBorderLineWidth());
g2.setStroke(stroke);
// back border
g2.setColor(s.getForeground());
Point p = new Point(0, 0);
// inner with gradient
Point2D start = new Point(width / 2, 0);
Point2D end = new Point(width / 2, height);
Paint paint = new GradientPaint(start, s.getForeground(), end,
ColorManager.brighter(s.getForeground(), 80));
g2.setPaint(paint);
int step = 1;
RoundRectangle2D rect = new RoundRectangle2D.Double(p.x, p.y, width
- (2 * step), height - (2 * step), s.getCornerSize(), s
.getCornerSize());
g2.fill(rect);
g2.setColor(ColorManager.darker(s.getForeground(), 20));
g2.draw(rect);
g2.setColor(ColorManager.getColorAlpha(s.getFontColor(), s.getFontAlpha()));
Point textPoint = FontManager.getCenterTextPosition(b.getText(), g2,
rect);
g2.drawString(b.getText(), textPoint.x, textPoint.y);
generateJPG(buffer, b.getFileName());
}
/**
* @param buffer
* @throws FileNotFoundException
* @throws IOException
*/
private static void generatePNG(BufferedImage buffer, String fileName)
throws FileNotFoundException, IOException {
FileOutputStream file = new FileOutputStream(fileName);
javax.imageio.ImageIO.write(buffer, "png", file);
file.close();
}
/**
* @param buffer
* @throws FileNotFoundException
* @throws IOException
*/
private static void generateJPG(BufferedImage buffer, String fileName)
throws FileNotFoundException, IOException {
FileOutputStream file = new FileOutputStream(fileName);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(file);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(buffer);
encoder.setJPEGEncodeParam(param);
encoder.encode(buffer);
file.close();
}
...
Vale ressaltar algumas classes que para mim eram novas e surgiram com a pesquisa sobre gráficos e desenhos em Java:
- BufferedImage – cria uma imagem em memória, já tinha usado na criação de certificados online do riojug
- setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) – para evitar o aliasing nas curvas das imagens (aquele serrilhado que fica nas curvas)
- GradientPaint - cria um degradee, tem um monte de opções !!
- javax.imageio.ImageIO – para criar imagens
Os links abaixo me ajudaram na pesquisa :
draw aqua buttons
http://home.zonnet.nl/epragt/tutorials/photoshop/shapesandobjects/macbutton/index.jsp.htm
http://home.zonnet.nl/epragt/tutorials/photoshop/shapesandobjects/aquabuttonpro/index.jsp.htm
xp style
http://www.infinite-fire.net/tutorials/photoshop/windows-xp-style-buttons
curves
http://www.infinite-fire.net/tutorials/photoshop/sexy-smooth-curves
circle
http://www.infinite-fire.net/tutorials/photoshop/inset-orb-effect
java image editor
http://www.jhlabs.com/ip/imageeditor.html