How to specify a rectangle from the CGPoint Start and End?

250 Views Asked by At

I have a rectangle bounds (10, 20, 100, 200) and the CGPoints are StartPoint (0.5, 0.5) and EndPoints as (1, 1). From these points how needs to calculate the segments bounds ? I need to apply this bounds for CGGradient for start point and end points.

Eg Code :

GradientColor gradientColor1 = new GradientColor(){StartPoint = new CGPoint(0.5, 0), EndPoint= new CGPoint(0.5, 1)};

GradientStop stop1 = new GradientStop() { Color = UIColor.Red, Offset = 0.1f };
GradientStop stop2 = new GradientStop() { Color = UIColor.Blue, Offset = 0.9f };

can you please help me out of this?

1

There are 1 best solutions below

0
On BEST ANSWER

Here an an example that will create a left to right linear gradient within the current CGContext.

using (var context = UIGraphics.GetCurrentContext ()) {
    context.SaveState();
    var startPoint = new CGPoint(rect.Left, 0);
    var endPoint = new CGPoint(rect.Right, 0);
    var components = new CGColor[] { UIColor.Red.CGColor, UIColor.Blue.CGColor };

    using (var rgb = CGColorSpace.CreateDeviceRGB()) {
        var gradient = new CGGradient(rgb, components);
        context.DrawLinearGradient(gradient, startPoint, endPoint, CGGradientDrawingOptions.DrawsBeforeStartLocation);
    };
    context.RestoreState();
}

Changing the start and end points you can have the gradient paint right to left, up/down, diagonal, etc..

enter image description here