2015-10-25 74 views
1

我想绘制一个出褪色透明椭圆高亮平铺屏幕上的瓷砖。遗憾的是我没能找到Swing已实现的功能,能做到这一点,所以我写了我自己:绘制出褪色透明椭圆

private void drawGradientedOval(Graphics2D g2d, Rectangle bounds) { 

    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 

    int loops = (int) Math.min(bounds.getWidth()/2, bounds.getHeight()/2); 
    int x = bounds.x + (int) (bounds.getWidth()/2); 
    int y = bounds.y + (int) (bounds.getHeight()/2); 
    int scale = 1; 
    float alpha = 0.5f; 
    float step = alpha/loops; 

    for (int i = 0; i < loops; i++) { 
     g2d.setColor(new Color(1f, 1f, 1f, alpha)); 
     g2d.drawOval(x--, y--, scale, scale); 
     scale += 2; 
     alpha -= step; 
    } 

} 

产生的椭圆形的样子(作物比椭圆形范围大):

enter image description here

结果不是一个光滑的椭圆形,有一个“十字”和一些其他小的文物。

我认为这是由彼此重叠绘制的“重叠”像素造成的。

有没有一种明智的方法来解决这个问题?

请注意,我宁愿避免实现像Raster级别上操纵单个像素的较低级别的解决方案,仅仅是因为这项工作涉及大量上述未提及的变量。

回答

4

为什么不使用RadialGradientPaint对象来绘画?喜欢的东西:

import java.awt.Color; 
import java.awt.Dimension; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.Paint; 
import java.awt.RadialGradientPaint; 
import javax.swing.*; 

@SuppressWarnings("serial") 
public class GradOval extends JPanel { 
    private static final int PREF_W = 400; 
    private static final int PREF_H = PREF_W; 
    private static final Color BG = Color.BLACK; 
    private static final float[] FRACTIONS = {0.0f, 1.0f}; 
    private static final Color[] COLORS = {Color.LIGHT_GRAY, new Color(0, 0, 0, 0)}; 

    public GradOval() { 
     setBackground(BG); 
    } 

    @Override 
    protected void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     float cx = getWidth()/2f; 
     float cy = getHeight()/2f; 
     float radius = cx;  
     Paint paint = new RadialGradientPaint(cy, cy, radius, FRACTIONS, COLORS); 
     Graphics2D g2 = (Graphics2D) g; 
     g2.setPaint(paint); 
     g2.fillRect(0, 0, getWidth(), getHeight());   
    } 

    @Override 
    public Dimension getPreferredSize() { 
     if (isPreferredSizeSet()) { 
      return super.getPreferredSize(); 
     } 
     return new Dimension(PREF_W, PREF_H); 
    } 

    private static void createAndShowGui() { 
     GradOval mainPanel = new GradOval(); 

     JFrame frame = new JFrame("GradOval"); 
     frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
     frame.getContentPane().add(mainPanel); 
     frame.pack(); 
     frame.setLocationByPlatform(true); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       createAndShowGui(); 
      } 
     }); 
    } 
} 

这将显示为:

enter image description here

+0

+1所付出的努力,但颜色之间的解决方案梯度。有没有办法将它与透明度一起使用?该解决方案不得覆盖以前的像素值。 –

+0

会设置'COLORS = {新颜色(1f,1f,1f,0.5f),新颜色(1f,1f,1f,0)'工作? –

+2

(1+)绘画@DimaMaligin - '会设置....工作?'你为什么不试试我?只有你知道确切的要求。 – camickr