如何在圆角矩形上绘制图像?(Java)



如何在圆角矩形上绘制缓冲图像?我覆盖了一个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);
}
}
}

备选方案只是某种颜色(可以是黑色的null(,并且只有在找不到图像/图像为null时才会绘制。请只考虑else部分。

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

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

最新更新