首页 > 解决方案 > 计算填充以使矩形居中对齐(按百分比调整大小)

问题描述

在此处输入图像描述

下面是我当前在画布空间(代表图标)中心对齐矩形(代表符号)的算法。这只是我感兴趣的算法,因此请忽略其余代码,因为它仅用于演示目的,作为视觉辅助。

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;
    }
    }
}

标签: javaalgorithmswing

解决方案


您的代码的问题是比例变换tran正在缩放矩形的计算原点,off以及sWidthsHeight。如果要保持当前方案,则需要将比例变换的逆应用于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;
}

请注意,我删除了它们padXpadY因为它们不是计算偏移量所必需的。


推荐阅读