How can I create a UIImage from scratch. Specifically, I want to create a UIImage of size 320x50. Then, I'd like to be able to draw polygons of specific color onto that image.
Here is an answer for you stitch picture in iphone
And base on my experience, I can give you some note:
Propotional scale
- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize { UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize,image.size.height*scaleSize); [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height *scaleSize)]; UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return scaledImage; }
Resize
- (UIImage *)reSizeImage:(UIImage *)image toSize:(CGSize)reSize { UIGraphicsBeginImageContext(CGSizeMake(reSize.width, reSize.height)); [image drawInRect:CGRectMake(0, 0, reSize.width, reSize.height)]; UIImage *reSizeImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return reSizeImage; }
Handle specific view
You hava to import QuzrtzCore.framework first
-(UIImage*)captureView:(UIView *)theView { CGRect rect = theView.frame; UIGraphicsBeginImageContext(rect.size); CGContextRef context = UIGraphicsGetCurrentContext(); [theView.layer renderInContext:context]; UIImage *img = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return img; }
Handle a range form image
CGRect captureRect = yourRect CGRect viewRect = self.view.frame; UIImage *viewImg; UIImage *captureImg; UIGraphicsBeginImageContext(viewRect.size); CGContextRef context = UIGraphicsGetCurrentContext(); [self.view.layer renderInContext:context]; viewImg = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); captureImg = [UIImage imageWithCGImage:CGImageCreateWithImageInRect(viewImg.CGImage, captureRect)];
Save the image
Save in app
NSString *path = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"image.png"]; [UIImagePNGRepresentation(image) writeToFile:path atomically:YES];
Save in album
CGImageRef screen = UIGetScreenImage(); UIImage* image = [UIImage imageWithCGImage:screen]; CGImageRelease(screen); UIImageWriteToSavedPhotosAlbum(image, self, nil, nil);
I leave here my answer, just in case this can help in the future. This answer is valid on iOS10+
extension UIImage {
static func image(with size: CGSize) -> UIImage {
UIGraphicsImageRenderer(size: size)
.image { $0.fill(CGRect(origin: .zero, size: size)) }
}
}
so you can do:
UIImage.image(with: CGSize(width: 320, height: 50))
My answer is inspired by this: https://stackoverflow.com/a/48441178/2000162
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With