我正在为这样的按钮设置图像:
let itemImageURL = "\(self.view.getServerPath())image?path=\(league.logo!)"
let url = NSURL(string: itemImageURL )
let data = NSData(contentsOfURL: url!)
button.setImage(UIImage(data: data!), forState: UIControlState.Normal)
它们出现在按钮文本之前,它正是我想要的。 但是如何让图像更小呢?
答案 0 :(得分:0)
将图像调整为按钮大小,并将其添加为背景图像
func resizeImageWithAspect(image: UIImage,size: CGSize)->UIImage
{
let oldWidth = image.size.width;
let oldHeight = image.size.height;
let scaleFactor = (oldWidth > oldHeight) ? size.width / oldWidth : size.height / oldHeight;
let newHeight = oldHeight * scaleFactor;
let newWidth = oldWidth * scaleFactor;
let newSize = CGSizeMake(newWidth, newHeight);
if UIScreen.mainScreen().respondsToSelector(#selector(NSDecimalNumberBehaviors.scale)){
UIGraphicsBeginImageContextWithOptions(newSize,false,UIScreen.mainScreen().scale);
}
else
{
UIGraphicsBeginImageContext(newSize);
}
image.drawInRect(CGRectMake(0, 0, newSize.width, size.height));
let newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
使用:
button.setBackgroundImage(resizeImageWithAspect(UIImage(data: data!)!,size:button.bounds.size), forState: .Normal);
button.contentMode = UIViewContentMode.ScaleAspectFit;
button.clipsToBounds = true;
警告强> 在您编写的代码中
let url = NSURL(string: itemImageURL )
let data = NSData(contentsOfURL: url!)
在main thread
中执行此操作是一个非常糟糕的主意!看看下一个代码:
let url = NSURL(string: "https://abrahampacana.files.wordpress.com/2013/10/quabbin-11.jpg")
print(NSDate().timeIntervalSince1970) //1463505118
let data = NSData(contentsOfURL: url!)
print(NSDate().timeIntervalSince1970) //1463505138
此次加载需
这是应用程序卡住的20秒,用户正在等待没有任何反应,没有任何响应。 你应该至少使用后台线程
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)) {
//this is background thread
let url = NSURL(string: "https://abrahampacana.files.wordpress.com/2013/10/quabbin-11.jpg")
let data = NSData(contentsOfURL: url!)
//now return to main thread to update the view
//UI should always update from main thread
dispatch_async(dispatch_get_main_queue()){
button.setImage(...)
}
}
另一种解决方案:使用NSURLSession
答案 1 :(得分:0)
答案在uiimage的scale参数中:
button.setImage(UIImage(data: data!, scale: 3), forState: UIControlState.Normal)