Here is a simple MonoTouch app that demonstrates how to use Quartz2D to draw custom progress bars. You can download the MonoDevelop project here.
This app shows how to draw a simple two color progress bar using alpha transparency and a simple two color gradient progress bar. There are sliders that let you control the colors, transparency level, and progress percentage. The code uses the CGBitmapContext class to create an image and loads it into UIImageView.
This is the function to create a basic progress bar:
[sourcecode language=”csharp”]
private UIImage makeProgressImage(int width, int height, float progress, CGColor baseColor, CGColor topColor)
{
//Create a CGBitmapContext object
CGBitmapContext ctx = new CGBitmapContext(IntPtr.Zero, width, height, 8, 4 * width, CGColorSpace.CreateDeviceRGB(), CGImageAlphaInfo.PremultipliedFirst);
//Draw a rectangle with the base color
ctx.SetFillColorWithColor(baseColor);
ctx.FillRect(new RectangleF(0,0, width, height));
//Calculate the width of the 2nd rectangle based on the progress
float percentWidth = width * progress;
//Draw the second rectangle with the top color
ctx.SetFillColorWithColor(topColor);
ctx.FillRect(new RectangleF(0, 0, percentWidth, height));
//return a UIImage object
return UIImage.FromImage(ctx.ToImage());
}
[/sourcecode]
This is the function to create a gradient progress bar:
[sourcecode language=”csharp”]
private UIImage makeGradientProgressImage(int width, int height, float progress, float[] components, float[] locations)
{
//Create a CGBitmapContext object
CGBitmapContext ctx = new CGBitmapContext(IntPtr.Zero, width, height, 8, 4 * width, CGColorSpace.CreateDeviceRGB(), CGImageAlphaInfo.PremultipliedFirst);
//Calculate the width of the rectangle based on the progress
float percentWidth = width * progress;
//Create a gradient object
CGGradient gradient = new CGGradient(CGColorSpace.CreateDeviceRGB(), components, locations);
//Draw a linear gradient to represent the progress bar
ctx.DrawLinearGradient(gradient, new PointF(0, 0), new PointF(percentWidth, 0), CGGradientDrawingOptions.DrawsBeforeStartLocation);
//return a UIImage object
return UIImage.FromImage(ctx.ToImage());
}
[/sourcecode]
Note that these functions are fairly generic and you should be able to reuse them in any of your applications. See the MonoDevelop project for examples on how to use them. They are also very simple and can be extended to draw “prettier” progress bars without too much effort. I’ll cover drawing pie charts in my next post.
Super stuff…exactly what i was looking for.
Pingback: MonoTouch.Info