1 /*******************************************************************************
2 * Copyright (c) 2007, 2011 Association for Decentralized Information Management in
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.utils.ui.gfx;
14 import java.awt.Color;
16 import java.awt.FontMetrics;
17 import java.awt.Graphics2D;
18 import java.awt.RenderingHints;
19 import java.awt.geom.Rectangle2D;
20 import java.awt.image.BufferedImage;
21 import java.awt.image.Raster;
23 import org.eclipse.jface.resource.ImageDescriptor;
24 import org.eclipse.swt.graphics.ImageData;
25 import org.eclipse.swt.graphics.PaletteData;
26 import org.simantics.utils.ObjectUtils;
28 public class TextImageDescriptor extends ImageDescriptor {
30 static final PaletteData _RGB = new PaletteData(0x00ff0000, 0x0000ff00, 0x000000ff);
33 public int width, height;
39 private transient int hash;
41 public TextImageDescriptor(String text, int width, int height,
42 String font, int fontSize,
48 this.fontSize = fontSize;
52 hash = text.hashCode() + 3*width + 5*height + 7*font.hashCode() + 11*fontSize + 13*style + 17*rgb;
56 public ImageData getImageData() {
57 ImageData id = new ImageData(width, height, 24, _RGB);
58 BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
59 Graphics2D g = (Graphics2D) bi.getGraphics();
60 g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
61 Font f = new Font(font, style, fontSize);
63 Color c = new Color(rgb);
65 FontMetrics fm = g.getFontMetrics(f);
66 Rectangle2D rect = fm.getStringBounds(text, g);
67 g.drawString(text, (float) ((width-rect.getWidth())/2), (float) ( (height/2) + (height-rect.getHeight())/2) );
70 Raster alpha = bi.getAlphaRaster();
71 for (int x=0; x<width; x++) {
72 for (int y=0; y<height; y++) {
73 int a = alpha.getSample(x, y, 0);
74 int rgb = bi.getRGB(x, y);
76 id.setPixel(x, y, rgb);
84 public int hashCode() {
89 public boolean equals(Object obj) {
90 if (obj instanceof TextImageDescriptor==false) return false;
91 TextImageDescriptor o = (TextImageDescriptor) obj;
92 if ( !ObjectUtils.objectEquals(text, o.text) ) return false;
93 if ( !ObjectUtils.objectEquals(font, o.font) ) return false;
94 return width==o.width && height==o.height && fontSize==o.fontSize && style==o.style && rgb==o.rgb;