Reputation: 10330
I have a custom UIImageView and when it constructed I would like to create an in memory or cached to the iDevice Image that is a Filled Rectangle of a specific color and then set it to the UIImageView's Image property.
I know how to draw this on a UIImage by overriding the Draw method and it would just draw on the current CGContext. However since I want to do this at the time the UIImageView is constructed I don't actually have a context I can draw on or anything since it is not visible yet.
Simply put I am wondering if there is a way to do this programmatically at construction of the custom UIImageView when the app starts before anything is displayed to the screen.
I am okay with answers in C# or Objective-C.
Upvotes: 4
Views: 1461
Reputation: 20153
Well, I can help you with the UIKit / Objective-C approach. As for .NET, I don't have the foggiest. UIKit has a few useful functions for programmatically generating UIImages. What you'll need to do is something like the following:
- (UIImage*)generateImage {
UIGraphicsBeginImageContext(someCGSize);
CGContextRef ctx = UIGraphicsGetCurrentContext();
// Draw whatever you want here with ctx, just like an overridden drawRect.
UIImage* generatedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return generatedImage;
}
Just make sure you call such a method from the main thread. That's the only caveat I can think of.
[Edit] The C#/MonoTouch version is:
UIImage GenerateImage ()
{
UIGraphics.BeginImageContext (new RectangleF (0, 0, 100, 100));
var ctx = UIGraphics.GetCurrentContext ();
// Draw into the ctx anything you want.
var image = UIGraphics.GetImageFromCurrentImageContext ();
UIGraphics.EndImageContext ();
return image;
}
Upvotes: 6