RoundRectangle2D剪辑不是很流畅

时间:2014-06-04 19:06:02

标签: java swing awt java-2d antialiasing

我有一个JPanel,我想要修剪角落,使其具有圆角。

这就是我在做什么。

((Graphics2D)g).setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(color);
Shape s = new RoundRectangle2D.Double(0, 0, width, height, arc, arc);
g.setClip(s);

请注意,我将clipping设置为RoundRectangle2D。此外,我正在设置anti-aliasing我的圆形边缘仍然是锯齿状的。

Soft clipping example此链接可以为图像执行柔和的圆角边缘。我如何将相同的内容应用于JPanel?

2 个答案:

答案 0 :(得分:1)

因为剪切没有别名,所以您会看到锯齿状边缘。试试边框:

 p.setBorder(new RoundedBorder(p.getBackground(), 2, 16));

其中RoundedBorder是从text bubble类改编的:

 class RoundedBorder extends AbstractBorder {

    private Color color;
    private int thickness = 4;
    private int radii = 8;
    private Insets insets = null;
    private BasicStroke stroke = null;
    private int strokePad;
    private int pointerPad = 4;
    RenderingHints hints;

    RoundedBorder(
            Color color, int thickness, int radii) {
        this.thickness = thickness;
        this.radii = radii;

        this.color = color;

        stroke = new BasicStroke(thickness);
        strokePad = thickness / 2;

        hints = new RenderingHints(
                RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);

        int pad = radii + strokePad;
        int bottomPad = pad + strokePad;
        insets = new Insets(pad, pad, bottomPad, pad);
    }

    @Override
    public Insets getBorderInsets(Component c) {
        return insets;
    }

    @Override
    public Insets getBorderInsets(Component c, Insets insets) {
        return getBorderInsets(c);
    }

    @Override
    public void paintBorder(
            Component c,
            Graphics g,
            int x, int y,
            int width, int height) {

        Graphics2D g2 = (Graphics2D) g;

        int bottomLineY = height - thickness;

        RoundRectangle2D.Double bubble = new RoundRectangle2D.Double(
                0 + strokePad,
                0 + strokePad,
                width - thickness,
                bottomLineY,
                radii,
                radii);

        Area area = new Area(bubble);

        g2.setRenderingHints(hints);

        Area spareSpace = new Area(new Rectangle(0, 0, width, height));
        spareSpace.subtract(area);
        g2.setClip(spareSpace);
        g2.clearRect(0, 0, width, height);
        g2.setClip(null);

        g2.setColor(color);
        g2.setStroke(stroke);
        g2.draw(area);
    }
}
}

答案 1 :(得分:0)

如果您想要消除锯齿的角落,请使用TexturePaint而不是剪裁。它与剪切相同,但速度更快。将它与抗别名一起使用。

只是Google" TexturePaint examples"。