好的,考虑到没有被广泛接受的方法来实现这个,我想出了这个解决方案,并将代码发布给任何想做类似事情的人。这段代码将把一张图片分成9个部分。4个角落将保持不变。4条边的中间部分将沿着边缘被拉伸或压缩。中心部分将在两个方向上被拉伸或压缩。当然,对于我来说,这个类的目的是压缩一个带有圆角的大图像,但保留圆角,而当图像简单缩小时,圆角几乎消失了。显然,对于像图片这样的图像来说,这没什么用处,但是对于具有自定义绘制和圆角边缘的组件,这似乎很有效。
这个类没有构造函数,你只需要调用一个修改后的图像即可。使用方法如下:
StretchedImage.stretch(image, new Insets(t,l,b,r), new Dimension(w,h), BufferedImage.TYPE_INT_ARGB);
使用insets参数确定在单个维度上修改的边缘周围的数量,将返回一个拉伸到所需尺寸的图像,角落保持不变,只有侧面在1个维度上被修改。也许有一种巧妙的方法来遍历图像列表,但是这样我可以更好地看到发生了什么。
public class StretchedImage{
public static Image stretch(Image image, Insets ins, Dimension dim, int hints){
BufferedImage bi = toBufferedImage(image, hints);
Image[][] img = new Image[3][3];
img[0][0] = bi.getSubimage(0, 0, ins.left, ins.top);
img[0][1] = bi.getSubimage(ins.left, 0, bi.getWidth() - ins.left - ins.right, ins.top);
img[0][2] = bi.getSubimage(bi.getWidth() - ins.right, 0, ins.right, ins.top);
img[1][0] = bi.getSubimage(0, ins.top, ins.left, bi.getHeight() - ins.top - ins.bottom);
img[1][1] = bi.getSubimage(ins.left, ins.top, bi.getWidth() - ins.left - ins.right, bi.getHeight() - ins.top - ins.bottom);
img[1][2] = bi.getSubimage(bi.getWidth() - ins.right, ins.top, ins.right, bi.getHeight() - ins.top - ins.bottom);
img[2][0] = bi.getSubimage(0, bi.getHeight() - ins.bottom, ins.left, ins.bottom);
img[2][1] = bi.getSubimage(ins.left, bi.getHeight() - ins.bottom, bi.getWidth() - ins.left - ins.right, ins.bottom);
img[2][2] = bi.getSubimage(bi.getWidth() - ins.right, bi.getHeight() - ins.bottom, ins.right, ins.bottom);
int w = dim.width - ins.left - ins.right;
int h = dim.height - ins.top - ins.bottom;
img[0][1] = img[0][1].getScaledInstance(w, img[0][1].getHeight(null), hints);
img[1][0] = img[1][0].getScaledInstance(img[1][0].getWidth(null), h, hints);
img[1][1] = img[1][1].getScaledInstance(w, h, hints);
img[1][2] = img[1][2].getScaledInstance(img[1][2].getWidth(null), h, hints);
img[2][1] = img[2][1].getScaledInstance(w, img[2][1].getHeight(null), hints);
BufferedImage finalImage = new BufferedImage(dim.width, dim.height, hints);
Graphics g = finalImage.getGraphics();
g.drawImage(img[0][0], 0, 0, null);
g.drawImage(img[0][1], ins.left, 0, null);
g.drawImage(img[0][2], dim.width - ins.right, 0, null);
g.drawImage(img[1][0], 0, ins.top, null);
g.drawImage(img[1][1], ins.left, ins.top, null);
g.drawImage(img[1][2], dim.width - ins.right, ins.top, null);
g.drawImage(img[2][0], 0, dim.height - ins.bottom, null);
g.drawImage(img[2][1], ins.left, dim.height - ins.bottom, null);
g.drawImage(img[2][2], dim.width - ins.right, dim.height - ins.bottom, null);
return (Image)finalImage;
}
public static BufferedImage toBufferedImage(Image image, int hints) {
BufferedImage bi = new BufferedImage(image.getWidth(null), image.getHeight(null), hints);
bi.getGraphics().drawImage(image, 0, 0, null);
return bi;
}
}