MonoTouch: Drawing custom progress bars.

原文:http://rlopezxl.com/2009/10/16/monotouch-drawing-custom-progress-bars/


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:

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());
}


This is the function to create a gradient progress bar:

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());
}


你可能感兴趣的:(object,function,quartz,float,Components,colors)