2014-02-07 111 views
2

我正在用java swing製作六角形瓷磚的平鋪遊戲板。我可以在this SOF線程的幫助下繪製多邊形。多邊形的紋理/背景圖像

現在我想添加背景圖像到這些六邊形,我完全不知道如何做到這一點。 Here是在「矩形」上繪製背景的教程,但我如何在Hexagon上執行相同的操作?

回答

3

像這樣:

Textured Shape

import java.awt.*; 
import java.awt.geom.AffineTransform; 
import java.awt.geom.GeneralPath; 
import java.awt.image.BufferedImage; 
import java.net.URL; 
import javax.imageio.ImageIO; 
import javax.swing.*; 

class TexturedShape { 

    public static BufferedImage getTexturedImage(
      BufferedImage src, Shape shp, int x, int y) { 
     Rectangle r = shp.getBounds(); 
     // create a transparent image with 1 px padding. 
     BufferedImage tmp = new BufferedImage(
       r.width+2,r.height+2,BufferedImage.TYPE_INT_ARGB); 
     // get the graphics object 
     Graphics2D g = tmp.createGraphics(); 
     // set some nice rendering hints 
     g.setRenderingHint(
       RenderingHints.KEY_ANTIALIASING, 
       RenderingHints.VALUE_ANTIALIAS_ON); 
     g.setRenderingHint(
       RenderingHints.KEY_COLOR_RENDERING, 
       RenderingHints.VALUE_COLOR_RENDER_QUALITY); 
     // create a transform to center the shape in the image 
     AffineTransform centerTransform = AffineTransform. 
       getTranslateInstance(-r.x+1, -r.y+1); 
     // set the transform to the graphics object 
     g.setTransform(centerTransform); 
     // set the shape as the clip 
     g.setClip(shp); 
     // draw the image 
     g.drawImage(src, x, y, null); 
     // clear the clip 
     g.setClip(null); 
     // draw the shape as an outline 
     g.setColor(Color.RED); 
     g.setStroke(new BasicStroke(1f)); 
     g.draw(shp); 
     // dispose of any graphics object we explicitly create 
     g.dispose(); 

     return tmp; 
    } 

    public static Shape getPointedShape(int points, int radius) { 
     double angle = Math.PI * 2/points; 

     GeneralPath p = new GeneralPath(); 
     for (int ii = 0; ii < points; ii++) { 
      double a = angle * ii; 

      double x = (Math.cos(a) * radius) + radius; 
      double y = (Math.sin(a) * radius) + radius; 
      if (ii == 0) { 
       p.moveTo(x, y); 
      } else { 
       p.lineTo(x, y); 
      } 
     } 
     p.closePath(); 

     return p; 
    } 

    public static void main(String[] args) throws Exception { 
     URL url = new URL("http://i.stack.imgur.com/7bI1Y.jpg"); 
     BufferedImage bi = ImageIO.read(url); 
     Shape hxgn = getPointedShape(6, 32); 
     final BufferedImage txtr = getTexturedImage(bi, hxgn, -200, -120); 
     Runnable r = new Runnable() { 
      @Override 
      public void run() { 

       JOptionPane.showMessageDialog(null, 
         new JLabel(new ImageIcon(txtr))); 
      } 
     }; 
     // Swing GUIs should be created and updated on the EDT 
     // http://docs.oracle.com/javase/tutorial/uiswing/concurrency 
     SwingUtilities.invokeLater(r); 
    } 
} 
+0

能否請您解釋一下 「設置形狀爲Graphics2D對象剪輯」 嗎?我一點都不明白 –

+0

意識到我已經忘記了一兩步,我決定通過實施它將我的清單列入「酸性測試」。有關完整的實現(見代碼),請參見上文。 –