java - SWT 合成/画布适合图像
问题描述
我正在尝试将图像适合可以随窗口调整大小的复合材料(或画布)。当它出现时,我想确保它不会弄乱纵横比,所以我编写了这段代码来覆盖打印功能:
bazaarMenu.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent event) {
Image image = SWTResourceManager.getImage(mainFrame.class, "/assets/SkyHub/resources/images/bazaarBackground.jpg");//get the image
int w = bazaarMenu.getClientArea().width;//composite width
int h = bazaarMenu.getClientArea().height;//composite height
int iw = image.getBounds().width;//image width
int ih = image.getBounds().height;// image height
//these are the values of the width/height of the image if ratio is same with the
//composite's
int w1 = ih * (w / h);
int h1 = iw * (h / w);
//Find which value can be used and draw the image
if(w1 <= w)
{
event.gc.drawImage(image, 0, 0, w1, ih, 0, 0, w, h);
}
else// if(w / h < 76 / 45)
{
event.gc.drawImage(image, 0, 0, iw, h1, 0, 0, w, h);
}
}
});
但是,我无法得到我想要的结果。可以看到图像拉伸或仅可以看到其中的一部分。有没有其他方法可以做,或者我错过了一些东西。
解决方案
修复它,问题是 int 太不准确,如果有人正在搜索比率代码,这里是代码:
bazaarMenu.addPaintListener(new PaintListener() {
@Override
public void paintControl(PaintEvent event) {
Image image = SWTResourceManager.getImage(mainFrame.class, "/assets/SkyHub/resources/images/bazaarBackground.jpg");
float w = bazaarMenu.getClientArea().width;
float h = bazaarMenu.getClientArea().height;
float iw = image.getBounds().width;
float ih = image.getBounds().height;
float a = 0;
if(w / h > iw / ih)
{
a = ih - (ih * w - iw * h) / w;
event.gc.drawImage(image, 0, (int)(ih - a) / 2, (int)iw, (int)a, 0, 0, (int)w, (int)h);
}
else
{
a = (w * ih) / h;
event.gc.drawImage(image, (int)(iw - a) / 2, 0, (int)a, (int)ih, 0, 0, (int)w, (int)h);
}
//event.gc.setFont(new Font( minionButton.getDisplay(), new FontData( "Arial", 10, SWT.BOLD )));
//event.gc.drawText(" Canvas W: " + w + "\n Canvas H: " + h + "\n Image W: " + iw + "\n Image H: " + ih + "\n a: " + a + "\n Mode: " + ((w / h > iw / ih)? "landscape" : "portrait") + "\n Canvas ratio: " + (w / h) + "\n Image ratio: " + (iw / ih), 5, 5);
}
});
推荐阅读
- reactjs - 如何用 Jest 模拟反应条带函数?
- java - 将 html 表单中的参数传递到 rest api 控制器 - null
- python - 如何在 matplotlib 中排列 x 轴的年份
- powershell - 从 Jenkins 管道调用 System.Net.Http.HttpClient.PutAsync - 空响应
- javascript - 如何重新运行 Blotter.js 的构建脚本?
- swiftui - 如何在 LazyHGrid 中的行之间添加视图分隔符?
- python - 使用不同的 Python API/函数在 Kubernetes 集群上进行操作
- python - 如何将列表乘以数据框的每一行?
- node.js - 使用 Dockerfile,为什么主机目录的内容没有覆盖容器工作目录?
- ios - apple-app-site-association - 文件扩展名?