Segment.java
上传用户:sdzznc
上传日期:2022-07-23
资源大小:51k
文件大小:3k
- // Copyright by Scot Drysdale
- package cn.edu.nju.software.grapheditor.shape;
- import java.awt.Color;
- import java.awt.Graphics;
- import java.awt.Point;
- public class Segment extends Shape {
- public Point startPoint,endPoint;
- public Segment(Color c) {
- super(c);
-
- // TODO Auto-generated constructor stub
- }
- public void drawShape(Graphics page) {
-
- page.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y);
- }
- // YOU FILL IN INSTANCE VARIABLES AND METHODS.
- /**
- * Helper method that returns true if Point p is within a tolerance of given
- * bounding box. Here, the bounding box is given by the coordinates of its
- * left, top, right, and bottom.
- */
- private static boolean almostContainsPoint(Point p, int left, int top,
- int right, int bottom, double tolerance) {
- return p.x >= left - tolerance && p.y >= top - tolerance
- && p.x <= right + tolerance && p.y <= bottom + tolerance;
- }
- // Helper method that returns the distance from Point p to the line
- // containing a line segment whose endpoints are given.
- private static double distanceToPoint(Point p, int x1, int y1, int x2,
- int y2) {
- if (x1 == x2) // vertical segment?
- return (double) (Math.abs(p.x - x1)); // yes, use horizontal
- // distance
- else if (y1 == y2) // horizontal segment?
- return (double) (Math.abs(p.y - y1)); // yes, use vertical distance
- else {
- // Here, we know that the segment is neither vertical nor
- // horizontal.
- // Compute m, the slope of the line containing the segment.
- double m = ((double) (y1 - y2)) / ((double) (x1 - x2));
- // Compute mperp, the slope of the line perpendicular to the
- // segment.
- double mperp = -1.0 / m;
- // Compute the (x, y) intersection of the line containing the
- // segment and the line that is perpendicular to the segment and
- // that
- // contains Point p.
- double x = (((double) y1) - ((double) p.y) - (m * x1) + (mperp * p.x))
- / (mperp - m);
- double y = m * (x - x1) + y1;
- // Return the distance between Point p and (x, y).
- return Math.sqrt(Math.pow(p.x - x, 2) + Math.pow(p.y - y, 2));
- }
- }
- public Point getCenter() {
- return new Point((startPoint.x+endPoint.x)/2,(startPoint.y+endPoint.y)/2);
- }
- public boolean containsPoint(Point p) {
- int left=Math.min(startPoint.x,endPoint.x);
- int right=Math.max(startPoint.x,endPoint.x);
- int top=Math.min(startPoint.y,endPoint.y);
- int bottom=Math.max(startPoint.y,endPoint.y);
- return almostContainsPoint(p,left,top,right,bottom,3.0)&&(distanceToPoint(p,startPoint.x,startPoint.y,endPoint.x,endPoint.y)<=3.0);
- }
- public void move(int deltaX, int deltaY) {
- startPoint.x+=deltaX;
- endPoint.x+=deltaX;
- startPoint.y+=deltaY;
- endPoint.y+=deltaY;
- }
- }