我想制作一个函数,将图像从矩形调整为正方形而不会产生扭曲。
这是我的代码: 我对该行有一个错误(表达式不符合“$ T4”类型):if(UIScreen.mainScreen()。respondsToSelector(aSelector:scaleTransform))
func squareImageFromImage(image:UIImage, newSize: CGFloat) -> UIImage {
var scaleTransform :CGAffineTransform
var origin : CGPoint
var scaleRatio: CGFloat
if (image.size.width > image.size.height) {
scaleRatio = newSize / image.size.height
scaleTransform = CGAffineTransformMakeScale(scaleRatio, scaleRatio);
origin = CGPointMake(-(image.size.width - image.size.height) / 2.0, 0)
} else {
scaleRatio = newSize / image.size.width
scaleTransform = CGAffineTransformMakeScale(scaleRatio, scaleRatio);
origin = CGPointMake(0, -(image.size.height - image.size.width) / 2.0)
}
var size: CGSize = CGSizeMake(newSize, newSize)
if (UIScreen.mainScreen().respondsToSelector(aSelector: scaleTransform)) {
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
} else {
UIGraphicsBeginImageContext(size)
}
var context: CGContextRef = UIGraphicsGetCurrentContext()
CGContextConcatCTM(context, scaleTransform)
image.drawAtPoint(origin)
var newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
答案 0 :(得分:0)
Swift中使用String
描述了一个选择器。
UIScreen.mainScreen().respondsToSelector(aSelector: "scaleTransform")
答案 1 :(得分:0)
在我的Objective-C
代码中,我会检查mainScreen
是否响应scale
选择器:
[[UIScreen mainScreen] respondsToSelector:@selector(scale)];
将其转换为 Swift ,如下所示:
UIScreen.mainScreen().respondsToSelector(Selector("scale"))
所以我认为代码中有问题的部分应如下所示:
if (UIScreen.mainScreen().respondsToSelector(Selector("scale"))) {
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
}
else {
UIGraphicsBeginImageContext(size)
}
希望有所帮助!
答案 2 :(得分:0)
下面的代码也适用于Swift 2.3和3.0
UIScreen.mainScreen().respondsToSelector(#selector(NSDecimalNumberBehaviors.scale))