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(int zoom) {
61 float s = zoom / 100.0f;
62 w = Math.round(width * s);
63 h = Math.round(height * s);
64 fs = Math.round(fontSize * s);
66 return getImageData(w, h, fs);
69 private ImageData getImageData(int width, int height, int fontSize) {
70 ImageData id = new ImageData(width, height, 24, _RGB);
72 BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
73 Graphics2D g = (Graphics2D) bi.getGraphics();
74 g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
75 Font f = new Font(font, style, fontSize);
77 Color c = new Color(rgb);
79 FontMetrics fm = g.getFontMetrics(f);
80 Rectangle2D rect = fm.getStringBounds(text, g);
81 g.drawString(text, (float) ((width-rect.getWidth())/2), (float) ( (height/2) + (height-rect.getHeight())/2) );
84 Raster alpha = bi.getAlphaRaster();
85 for (int x=0; x<width; x++) {
86 for (int y=0; y<height; y++) {
87 int a = alpha.getSample(x, y, 0);
88 int rgb = bi.getRGB(x, y);
90 id.setPixel(x, y, rgb);
98 public int hashCode() {
103 public boolean equals(Object obj) {
104 if (obj instanceof TextImageDescriptor==false) return false;
105 TextImageDescriptor o = (TextImageDescriptor) obj;
106 if ( !ObjectUtils.objectEquals(text, o.text) ) return false;
107 if ( !ObjectUtils.objectEquals(font, o.font) ) return false;
108 return width==o.width && height==o.height && fontSize==o.fontSize && style==o.style && rgb==o.rgb;