我使用此方法调整图像大小
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 :(得分: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;
}