2017-09-26 115 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表示形式,然後工作,但謝謝! –