2017-09-26 61 views
2

我试图让图像的角落变圆,但来自ImageContext的图像变形。ImageContext返回图像失真

这是我采取的步骤:

- (UIImage *)decodeBase64ToImage:(NSString *)strEncodedData 
{ 
    NSURL *url = [NSURL URLWithString:strEncodedData]; 
    NSData* data = [[NSData alloc] initWithContentsOfURL:url]; 
    UIImage* image = [[UIImage alloc] initWithData:data]; 
    UIImage* croppedImage = [self makeRoundedImage:image]; 
    return croppedImage; 
} 

- (UIImage *)makeRoundedImage:(UIImage *) image 
{ 

    CGRect frame = CGRectMake(0, 0, image.size.width, image.size.height); 

    UIGraphicsBeginImageContext(frame.size); 
    //[[UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, image.size.width, image.size.height) cornerRadius:10.0] addClip]; 
    [image drawInRect:frame]; 

    // Get the image 
    UIImage *croppedImage = UIGraphicsGetImageFromCurrentImageContext(); 

    // Lets forget about that we were drawing 
    UIGraphicsEndImageContext(); 

    return croppedImage; 
} 
+0

我觉得没有必要让UIImage的角落。你需要制作UIImageView的角落。 –

+0

@YogendraGirase我不能使用UIImageView,我需要在只与UIImage一起工作的框架中使用它。 –

+0

您可以在下面检查我的答案。它可能对您有所帮助 –

回答

0

您可以检查此方法

-(UIImage *)roundedImage:(UIImage *) roundImage 
         radius: (float) radius; 
{ 
    CALayer *imageLayer = [CALayer layer]; 
    imageLayer.frame = CGRectMake(0, 0, roundImage.size.width, roundImage.size.height); 
    imageLayer.contents = (id) roundImage.CGImage; 

    imageLayer.masksToBounds = YES; 
    imageLayer.cornerRadius = radius; 

    UIGraphicsBeginImageContext(roundImage.size); 
    [imageLayer renderInContext:UIGraphicsGetCurrentContext()]; 
    UIImage *finalRoundedImage = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 

    return finalRoundedImage; 
} 
0

尝试。

-(UIImage *)imageWithRoundedCorner:(float)cornerRadius Image:(UIImage *)realImage 
{ 
    UIImageView *imageView = [[UIImageView alloc] initWithImage:realImage]; 
    UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, 1.0); 
    [[UIBezierPath bezierPathWithRoundedRect:imageView.bounds cornerRadius:cornerRadius] addClip]; 
    [realImage drawInRect:imageView.bounds]; 
    imageView.image = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 
    return imageView.image; 
} 
0

试试这个,这将解决图像失真的问题..

- (UIImage *)makeRoundedImage:(UIImage *) image 
{ 

    CGRect frame = CGRectMake(0, 0, image.size.width, image.size.height); 

UIGraphicsBeginImageContextWithOptions(frame.size, NO, 0); 
    //[[UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, image.size.width, image.size.height) cornerRadius:10.0] addClip]; 
    [image drawInRect:frame]; 

    // Get the image 
    UIImage *croppedImage = UIGraphicsGetImageFromCurrentImageContext(); 

    // Lets forget about that we were drawing 
    UIGraphicsEndImageContext(); 

    return croppedImage; 
} 
+0

我发现这个问题,我的其他框架没有直接从ImageContext接受UIImage,所以我不得不将它转换为PNG表示形式,然后工作,但谢谢! –