How to calculate correct endpoint

The attached project is working here.( https://www.dropbox.com/s/uhyr9d64gaieo25/brush.xojo_binary_project?dl=0)

The math behind the select case is based on the geometry shown by Norman’s video. Starting from the angle (defined by the slider), determine the slope of the line that passes through the center, and then the slope of the two lines perpendicular to the first line. Then it’s a matter of creating straight lines with a certain slope passing through a point (the center or the corners of the rectangle) and finding their intersection.

HTH,

Julen

2 Likes

@Julen_I, you made my day. Thank you very much for your explanation and the sample project. :ok_hand:

Here is the code in case anyone needs it in the future and I have removed the project from my dropbox:

g.DrawRectangle(1, 1, me.width-1, me.height-1)
Const rad As Double = 0.0174533

Var grad As New LinearGradientBrush
grad.GradientStops.Add(New Pair(0, Color.Green))
grad.GradientStops.Add(New Pair(0.25, Color.Red))
grad.GradientStops.Add(New Pair(0.5, Color.Yellow))
grad.GradientStops.Add(New Pair(0.75, Color.Magenta))
grad.GradientStops.Add(New Pair(1.0, Color.Blue))

Var angle As Double = Slider1.Value * rad ' Slider1 in degree 0-360
Var Slope as double=Tan(angle)

Var origin As new point(100,100)
Var extreme as new point(200,300)

Var Cx As Double = (extreme.x+origin.x) / 2.0
Var Cy As Double = (extreme.y+origin.y)  / 2.0

Var X1,y1,x2,y2 as double

select case slider1.value
  
case 0, 360
  X1= origin.x
  y1= cy
  x2= extreme.x
  y2= cy
  
Case 1 to 89
  X1 = (slope*Cx+origin.y+origin.x/slope-Cy)/(1/slope+slope)
  y1 = x1*slope+ Cy-slope*cx
  x2 = (slope*Cx+extreme.y+extreme.x/slope-Cy)/(1/slope+slope)
  y2 = x2*slope+ Cy-slope*cx
  
case 90
  X1= Cx
  y1= origin.Y
  x2= cx
  y2= extreme.y
  
case 91 to 179
  X1 = (slope*Cx+origin.y+extreme.x/slope-Cy)/(1/slope+slope)
  y1 = x1*slope+ Cy-slope*cx
  x2 = (slope*Cx+extreme.y+origin.x/slope-Cy)/(1/slope+slope)
  y2 = x2*slope+ Cy-slope*cx
  
case 180
  X2= origin.x
  y2= cy
  x1= extreme.x
  y1= cy
  
Case 181 to 269
  X2 = (slope*Cx+origin.y+origin.x/slope-Cy)/(1/slope+slope)
  y2 = x2*slope+ Cy-slope*cx
  x1 = (slope*Cx+extreme.y+extreme.x/slope-Cy)/(1/slope+slope)
  y1 = x1*slope+ Cy-slope*cx
  
case 270
  X2= Cx
  y2= origin.Y
  x1= cx
  y1= extreme.y
  
case 271 to 359
  X2 = (slope*Cx+origin.y+extreme.x/slope-Cy)/(1/slope+slope)
  y2 = x2*slope+ Cy-slope*cx
  x1 = (slope*Cx+extreme.y+origin.x/slope-Cy)/(1/slope+slope)
  y1 = x1*slope+ Cy-slope*cx
  
end Select

grad.StartPoint = New Point(x1,y1)
grad.EndPoint = New Point(x2,y2)

g.Brush = grad
g.FillRectangle(origin.X, origin.y, extreme.x-origin.x, extreme.y-origin.y)

g.Brush = Nil
g.FillOval(grad.StartPoint.X - 5, grad.StartPoint.Y - 5, 10, 10)
g.FillOval(grad.EndPoint.X - 5, grad.EndPoint.Y - 5, 10, 10)