2016-09-26 126 views
0

我已經使用這個方法來調整圖像大小調整圖像以適應背景

extension UIColor { 
    static func imageWithBackgroundColor(image: UIImage, bgColor: UIColor) -> UIColor { 
     let size = CGSize(width: 70, height: 70) 

     UIGraphicsBeginImageContextWithOptions(size, false, 0) 
     let context = UIGraphicsGetCurrentContext() 


     let rectangle = CGRect(x: 0, y: 0, width: size.width, height: size.height) 

     CGContextSetFillColorWithColor(context, bgColor.CGColor) 
     CGContextAddRect(context, rectangle) 
     CGContextDrawPath(context, .Fill) 

     CGContextDrawImage(context, rectangle, image.CGImage) 

     let img = UIGraphicsGetImageFromCurrentImageContext() 
     UIGraphicsEndImageContext() 

     return UIColor(patternImage: img) 
    } 
} 

func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? { 
    let delete = UITableViewRowAction(style: .Default, title: "Delete") { (action, indexPath) in 

    // do some action 
    // 
    if let buttonImage = UIImage(named: "myImage") { 
     delete.backgroundColor = UIColor.imageWithBackgroundColor(image: buttonImage, bgColor: UIColor.blueColor()) 
    } 
    return [delete] 
} 

然而,圖像是上下顛倒了這種方法。有什麼想法嗎?任何人都可以幫助修改它,或者提出其他方法來調整圖像的大小,使其完全適合背景。

回答

0
- (UIImage *)resizeImage:(UIImage *)image 
    withMaxDimension:(CGFloat)maxDimension 
{ 
if (fmax(image.size.width, image.size.height) <= maxDimension) { 
    return image; 
} 

CGFloat aspect = image.size.width/image.size.height; 
CGSize newSize; 

if (image.size.width > image.size.height) { 
    newSize = CGSizeMake(maxDimension, maxDimension/aspect); 
} else { 
    newSize = CGSizeMake(maxDimension * aspect, maxDimension); 
} 

UIGraphicsBeginImageContextWithOptions(newSize,NO,0); 
CGRect newImageRect = CGRectMake(0.0, 0.0, newSize.width, newSize.height); 
[image drawInRect:newImageRect]; 
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

return newImage; 
} 

    /////// OR //// 

- (UIImage *)image:(UIImage*)originalImage scaledToSize:(CGSize)size 
{ 
    //avoid redundant drawing 
if (CGSizeEqualToSize(originalImage.size, size)) 
{ 
    return originalImage; 
} 

//create drawing context 
UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f); 

//draw 
[originalImage drawInRect:CGRectMake(0.0f, 0.0f, size.width, size.height)]; 

//capture resultant image 
UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

//return image 
return image; 
}