1 36 37 40 41 package java2d.demos.Colors; 42 43 import java.awt.*; 44 import java.awt.geom.Rectangle2D ; 45 import java.awt.color.ColorSpace ; 46 import java.awt.image.BufferedImage ; 47 import java.awt.image.ColorConvertOp ; 48 import java.awt.font.TextLayout ; 49 import java.awt.font.FontRenderContext ; 50 import java2d.Surface; 51 52 import static java.awt.Color .*; 53 54 55 59 public class ColorConvert extends Surface { 60 61 private static Image img; 62 private static Color colors[] = { red, pink, orange, 63 yellow, green, magenta, cyan, blue}; 64 65 66 public ColorConvert() { 67 setBackground(white); 68 img = getImage("clouds.jpg"); 69 } 70 71 72 public void render(int w, int h, Graphics2D g2) { 73 74 int iw = img.getWidth(this); 75 int ih = img.getHeight(this); 76 FontRenderContext frc = g2.getFontRenderContext(); 77 Font font = g2.getFont(); 78 g2.setColor(black); 79 TextLayout tl = new TextLayout ("ColorConvertOp RGB->GRAY", font, frc); 80 tl.draw(g2, (float) (w/2-tl.getBounds().getWidth()/2), 81 tl.getAscent()+tl.getLeading()); 82 83 BufferedImage srcImg = 84 new BufferedImage (iw, ih, BufferedImage.TYPE_INT_RGB); 85 Graphics2D srcG = srcImg.createGraphics(); 86 RenderingHints rhs = g2.getRenderingHints(); 87 srcG.setRenderingHints(rhs); 88 srcG.drawImage(img, 0, 0, null); 89 90 String s = "JavaColor"; 91 Font f = new Font("serif", Font.BOLD, iw/6); 92 tl = new TextLayout (s, f, frc); 93 Rectangle2D tlb = tl.getBounds(); 94 char[] chars = s.toCharArray(); 95 float charWidth = 0.0f; 96 int rw = iw/chars.length; 97 int rh = ih/chars.length; 98 for (int i = 0; i < chars.length; i++) { 99 tl = new TextLayout (String.valueOf(chars[i]), f, frc); 100 Shape shape = tl.getOutline(null); 101 srcG.setColor(colors[i%colors.length]); 102 tl.draw(srcG, (float) (iw/2-tlb.getWidth()/2+charWidth), 103 (float) (ih/2+tlb.getHeight()/2)); 104 charWidth += (float) shape.getBounds().getWidth(); 105 srcG.fillRect(i*rw, ih-rh, rw, rh); 106 srcG.setColor(colors[colors.length-1-i%colors.length]); 107 srcG.fillRect(i*rw, 0, rw, rh); 108 } 109 110 ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY); 111 ColorConvertOp theOp = new ColorConvertOp (cs, rhs); 112 113 BufferedImage dstImg = 114 new BufferedImage (iw, ih, BufferedImage.TYPE_INT_RGB); 115 theOp.filter(srcImg, dstImg); 116 117 g2.drawImage(srcImg, 10, 20, w/2-20, h-30, null); 118 g2.drawImage(dstImg, w/2+10, 20, w/2-20, h-30, null); 119 } 120 121 122 public static void main(String s[]) { 123 createDemoFrame(new ColorConvert()); 124 } 125 } 126 | Popular Tags |