我想找一条线。我使用鼠标事件初始化坐标x1,y1,x2,y2。当我试图找到如下所示的距离时:
public class LineFunctions {
static int dpi;
static double pixel_per_cm;
public LineFunctions(){
Toolkit tk;
tk=Main.frame.getToolkit();
dpi=tk.getScreenResolution();
pixel_per_cm=dpi/2.54;
}
public double lengthInPixel(int x1,int y1,int x2,int y2){
double length_in_pixel;
double x=Math.pow((x2-x1), 2);
double y=Math.pow((y2-y1), 2);
length_in_pixel = Math.sqrt(x+y);
return length_in_pixel;
}
public double lengthInCm(int x1,int y1,int x2,int y2){
double length_in_pixel=lengthInPixel(x1,y1,x2,y2);
double length_in_cm = length_in_pixel / pixel_per_cm;
System.out.println("Length in Cm= "+length_in_cm);
return length_in_cm;
}
}
Main.java
public class Main {
public static JFrame frame;
public static void main(String ar[]) {
frame=new JFrame("LINE FRAME");
}
static class ImageComponent extends JComponent implements MouseListener {
Line2D line;
int x1,y1,x2,y2;
public ImageComponent() {
addMouseListener(this);
addMouseMotionListener(this);
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D gd=(Graphics2D)g;
line=new Line2D.Double(x1,y1,x2,y2);
gd.draw(line);
}
@Override
public void mousePressed(MouseEvent e) {
x1=e.getX();
y1=e.getY();
}
@Override
public void mouseReleased(MouseEvent e) {
x2=e.getX();
y2=e.getY();
LineFunctions lf=new LineFunctions();
double length=lf.lengthInCm(x1,y1,x2,y2);
System.out.println("Line Length="+length);
repaint();
}
.......................
........................
}
此代码从坐标中查找线条的长度,但是当我从 RULER 中找到我在屏幕上绘制的线条的长度时,它看不到我的长度与我从上面的代码。那么,这有什么问题,我怎样才能找到确切的线长?
答案 0 :(得分:2)
您可以使用GraphicsConfiguration
GraphicsDevice
的{{3}}来确定所需的几何图形。特别是,标识转换表示“用户空间中的72个单位等于设备空间中的1英寸。”
另请考虑getNormalizingTransform()
以获得更高的准确性。