首页 > 解决方案 > 如何在圆角矩形上绘制图像?(爪哇)

问题描述

如何将缓冲图像绘制到圆角矩形上?我重写了一个paintComponent 方法,但调用graphics.setClip(new RoundRectangle2D.Double(0, 0, getWidth()-1,getHeight()-1, getArcRadius(),getArcRadius()));不起作用,因为圆角矩形不是矩形,而setClip 方法仅适用于矩形。

到目前为止的代码:

@Override
protected void paintComponent(Graphics g) {
    if (g instanceof Graphics2D) {
        //Render smooth
        Graphics2D graphics = (Graphics2D) g;
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        if(image == null) {
            //Draw alternative color
            graphics.setColor(alternative);
            graphics.fillRoundRect(0, 0, getWidth()-1, getHeight()-1, getArcRadius(),
                    getArcRadius());
        } else {
            //Draw image
            graphics.setClip(new RoundRectangle2D.Double(0, 0, getWidth()-1,getHeight()-1, getArcRadius(),
                    getArcRadius()));

            graphics.drawImage(image, 0, 0, null);
        }
    }
}

替代只是某种颜色(可以是黑色的空),并且仅在无法找到图像/为空时绘制。请只看else部分。

标签: javagraphics

解决方案


使用 clip() 而不是 setClip()。较新的 clip() 方法接受任意形状。

        graphics.clip(new RoundRectangle2D.Double(0, 0, getWidth()-1,getHeight()-1, getArcRadius(),
                getArcRadius()));

推荐阅读