创建特定大小的UIImage

时间:2012-01-16 08:33:29

标签: iphone ios uiimage polygon

如何从头开始创建UIImage。具体来说,我想创建一个大小为320x50的UIImage。然后,我希望能够在该图像上绘制特定颜色的多边形。

3 个答案:

答案 0 :(得分:5)

以下是您的答案stitch picture in iphone

根据我的经验,我可以给你一些注意事项:

比例尺

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

<强>调整大小

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

处理特定视图

您首先要导入QuzrtzCore.framework

-(UIImage*)captureView:(UIView *)theView
{
 CGRect rect = theView.frame; 
 UIGraphicsBeginImageContext(rect.size); 
 CGContextRef context = UIGraphicsGetCurrentContext(); 
 [theView.layer renderInContext:context]; 
 UIImage *img = UIGraphicsGetImageFromCurrentImageContext(); 
 UIGraphicsEndImageContext(); 
 return img;
}

处理范围表单图片

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)];

保存图片

保存在应用

NSString *path = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"image.png"];
[UIImagePNGRepresentation(image) writeToFile:path atomically:YES];

保存在相册

CGImageRef screen = UIGetScreenImage();
UIImage* image = [UIImage imageWithCGImage:screen];
CGImageRelease(screen);
UIImageWriteToSavedPhotosAlbum(image, self, nil, nil);

答案 1 :(得分:2)

你可以:

  1. 使用您需要的颜色/像素/尺寸/等创建CGBitmapContext
  2. 使用上下文或直接操作像素。
  3. 使用UIImage
  4. 的结果创建CGBitmapContextCreateImage

答案 2 :(得分:0)

我在这里留下我的答案,以防万一将来对您有所帮助。此答案在iOS10 +上有效

extension UIImage {
    static func image(with size: CGSize) -> UIImage {
        UIGraphicsImageRenderer(size: size)
            .image { $0.fill(CGRect(origin: .zero, size: size)) }
    }
}

因此您可以执行以下操作: UIImage.image(with: UIImage.image(with: CGSize(width: 320, height: 50)))

我的答案受此启发:https://stackoverflow.com/a/48441178/2000162