I am using “DrawLinearGradient” function to draw g

2019-03-04 18:07发布

问题:

I am using "DrawLinearGradient" function to draw gradient line. But the 2 colors that i am using are not dividing equally in the line.

CGColorSpace colorSpace = CGColorSpace.CreateDeviceRGB();
CGColor[] colors = {UIColor.Red.CGColor,UIColor.Green.CGColor};
float[] locations = {0.0f,0.5f,0.5f,1.0f};

CGGradient gradient = new CGGradient(colorSpace,colors,locations);
ColorMessage.FontSize = width;
context.SetLineWidth(width);
context.SaveState();
context.Clip();

context.DrawLinearGradient(gradient,penVertices[0],penVertices[count-1],0);

context.StrokePath();
gradient.Dispose();
colorSpace.Dispose();
context.RestoreState();

回答1:

I'm assuming that the Mono implementation has the same requirements as the original C implementation.

From the documentation of CGGradientCreateWithColors(colorSpace, colors, locations[]) (that should correspond to new CGGradient(colorSpace,colors,locations); in Mono) you can read

The locations array should contain the same number of items as the colors array.

In your code however you are passing two colors but four locations.

Since you are saying "dividing equally in the line" you should probably repeat both colors twice.

CGColor[] colors = {UIColor.Red.CGColor, UIColor.Red.CGColor, UIColor.Green.CGColor ,UIColor.Green.CGColor};
float[] locations = {0.0f,0.5f,0.5f,1.0f};