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);
}
}
}
替代只是某种颜色(可以是黑色的空),并且仅在无法找到图像/为空时绘制。请只看else
部分。
解决方案
使用 clip() 而不是 setClip()。较新的 clip() 方法接受任意形状。
graphics.clip(new RoundRectangle2D.Double(0, 0, getWidth()-1,getHeight()-1, getArcRadius(),
getArcRadius()));
推荐阅读
- python - 模拟在不同模块中导入的类
- spring-boot - Spring Cloud Zuul 网关无法在响应中添加自定义标头
- android - 什么是支持兼容库的 AndroidX 等价物?
- python - dblpy 事件未被调用
- javascript - 在 Vuetify 中垂直对齐多个 v-slide-group
- javascript - 谁能解释一下这段代码的输出?
- c# - URL has been blocked by CORS policy
- http - 是否有必要为 Web 应用程序中的所有页面包含 Cache-Control 标头?
- c++ - 带有 Rcpp 的 R 包
- google-chrome - 使用 Chrome 激活 Gmail 消息或打开新的 Gmail 消息窗口