java - 计算填充以使矩形居中对齐(按百分比调整大小)
问题描述
下面是我当前在画布空间(代表图标)中心对齐矩形(代表符号)的算法。这只是我感兴趣的算法,因此请忽略其余代码,因为它仅用于演示目的,作为视觉辅助。
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class IconSymbol extends JFrame {
public IconSymbol(double iWH, double s, double w, double h) {
getContentPane().add(new Canvas((int)iWH, s, w, h));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize((int)iWH, (int)iWH);
setVisible(true);
}
public static void main(String arg[]) {
IconSymbol is = new IconSymbol(100, 0.9, 50, 50);
}
class Canvas extends JPanel {
// STIPULATED
double iconWH = 0;
double sScale = 0;
double sWidth = 0;
double sHeight = 0;
// CALCULATED
double padX = 0;
double padY = 0;
double xOffSet = 0;
double yOffSet = 0;
public Canvas(double iWH,double sS,double sW,double sH) {
this.iconWH = iWH;
this.sScale = sS;
this.sWidth = sW;
this.sHeight = sH;
}
public void paint(Graphics g) {
Graphics2D g2D = (Graphics2D) g;
g2D.setBackground(Color.WHITE);
g2D.setPaint(Color.BLUE);
Shape icon = new Rectangle.Double(0,0,(int)iconWH,(int)iconWH);
g2D.fill(icon);
g2D.setPaint(Color.BLACK);
int width = (int)iconWH / 10;
int height= (int)iconWH / 10;
for(int row=0;row<10;row++){
for(int col=0;col<10;col++){
g.drawRect(row*width,col*height,width,height);
}
}
Point off = algorithm();
g2D.setPaint(Color.RED);
Shape s = new Rectangle.Double(off.x,off.y,(int)sWidth,(int)sHeight);
AffineTransform tran = AffineTransform.getScaleInstance(sScale, sScale);
g2D.fill(tran.createTransformedShape(s));
}
public Point algorithm(){
// ALGORITHM WITH EXACT NEEDED PARAMETERS
padX = (sWidth - ((sWidth * sScale))) / 2;
padY = (sHeight - ((sHeight * sScale))) / 2;
xOffSet = padX + ((iconWH - (sWidth * sScale)) / 2);
yOffSet = padX + ((iconWH - (sHeight * sScale)) / 2);
Point point = new Point((int)xOffSet, (int)yOffSet);
return point;
}
}
}
解决方案
您的代码的问题是比例变换tran
正在缩放矩形的计算原点,off
以及sWidth
和sHeight
。如果要保持当前方案,则需要将比例变换的逆应用于algorithm
方法中的计算偏移量:
public Point algorithm(){
// ALGORITHM WITH EXACT NEEDED PARAMETERS
xOffSet = ((iconWH - (sWidth * sScale)) / 2) / sScale;
yOffSet = ((iconWH - (sHeight * sScale)) / 2) / sScale;
Point point = new Point((int)xOffSet, (int)yOffSet);
return point;
}
请注意,我删除了它们padX
,padY
因为它们不是计算偏移量所必需的。
推荐阅读
- ios - AVPlayer addPeriodicTimeObserverForInterval:queue:usingBlock: 不会停止
- plotly - 如果 Atom 没有在文件夹中找到 .csv 文件,我该怎么办?
- python-3.x - 删除所有与用户相关的任务
- php - 如何使用 php 文件连接到 Android 上的 MediaPlayer
- sql - 当我们使用加法赋值 (+=) 时更新空值
- html - 视差效果:一个 div 在另一个 div 上?
- reactjs - 反应状态更新未定义并且不渲染
- macros - Lisp 宏找不到适用的函数
- python - 有没有办法使用 react js 前端来调用烧瓶安全功能?
- angular - Angular FormArray 索引未传递到输入文件类型更改事件