System.Drawing.Point operator error [duplicate]

2019-09-15 02:00发布

问题:

Possible Duplicate:
How to make the + operator work while adding two Points to each other?

my code

position.Location = (e.Location + pic1.Location) - bild_posi.Location;

error smth like:

the operator "+" isnt compatible with "System.Drawing.Point + System.Drawing.Point"

how can i fix this?

回答1:

It Depends on how you want to add points together

You could write a method called AddPoints and one called SubtractPoints such as

private Point AddPoints(Point A, Point B)
{
    return new Point(A.X + B.X, A.Y + B.Y);
}

private Point SubtractPoints(Point A, Point B)
{
    return new Point(A.X - B.X, A.Y - B.Y);
}

and then use it like

position.Location = SubtractPoints(AddPoints(e.Location,pic1.Location),bild_posi.Location);


回答2:

The System.Drawing.Point structure does not define an overload of the addition operator that takes two Point objects as parameters.

There is an addition operator that accepts a Point object and a Size object, and then adds the pair of numbers contained in the Size object to the values of the Point object. The documentation for that function is available here.

You can use that version by converting your second Point object to a Size object. This is pretty easy, since the Size structure provides an explicit conversion operator for Point, so all you have to do is cast your second Point object to a Size object:

position.Location = (e.Location + (Size)pic1.Location) - (Size)bild_posi.Location;

Note that I had to do the same thing for the third Point object, since the subtraction operator is implemented the same way as the addition operator.

Unfortunately, you cannot overload existing operators in C#, but you could create a regular old function that contains the logic internally, and then call that instead of using an operator. You could even make this an extension method of the Point class.

Edit: Nuts, it turns out I've answered this one already.



回答3:

Think of a point as an x/y coordinate on a graph. Unfortunately, you can't just add PointA and PointB to get PointC on the graph.

You need to calculate the x and y coordinates separately to achieve what you are going for.

With that said, try the following

var pointA = new Point(e.Location.X + pic1.Location.X, e.Location.Y + pic1.Location.Y);
var pointB = new Point(pointA.Location.X - bild_posi.Location.X, pointA.Location.Y - bild_posi.Location.Y);
position.Location = pointB;