我用于测试目的的应用程序能够拍照并将其保存为 PNG 文件。下次启动应用程序时,它会检查文件是否存在,如果存在,则将存储在文件中的图像用作应用程序的背景视图。到目前为止一切正常。
我决定在这个应用程序中添加一个剪贴蒙版,这就是出错的地方。剪裁本身可以工作,但由于某种神秘的原因,剪裁的图像被扩展了。如果有人能告诉我我做错了什么,那将非常有帮助。
这是相关代码(如果需要,我可以提供更多信息):
if let videoConnection = stillImageOutput.connectionWithMediaType(AVMediaTypeVideo) {
stillImageOutput.captureStillImageAsynchronouslyFromConnection(videoConnection) {
(imageDataSampleBuffer, error) -> Void in
if error == nil {
var localImage = UIImage(fromSampleBuffer: imageDataSampleBuffer)
var imageSize = CGSize(width: UIScreen.mainScreen().bounds.height * UIScreen.mainScreen().scale,
height: UIScreen.mainScreen().bounds.width * UIScreen.mainScreen().scale)
localImage = resizeImage(localImage!, toSize: imageSize)
imageSize = CGSize(width: imageSize.height, height: imageSize.width)
UIGraphicsBeginImageContext(imageSize)
CGContextRotateCTM (UIGraphicsGetCurrentContext(), CGFloat(M_PI_2))
localImage!.drawAtPoint(CGPoint(x: 0.0, y: -imageSize.width))
localImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// Clipping code:
localImage = maskImage(localImage!,
path: UIBezierPath(CGPath: CGPathCreateWithEllipseInRect(UIScreen.mainScreen().bounds, nil)))
if let data = UIImagePNGRepresentation(localImage!) {
data.writeToFile(self.bmpFilePath, atomically: true)
}
} else {print("Error on taking a picture:\n\(error)")}
}
}
maskImage 函数是这样的(取自iOS UIImage 剪辑到路径并翻译为 Swift):
func maskImage(originalImage :UIImage, path:UIBezierPath) -> UIImage {
UIGraphicsBeginImageContextWithOptions(originalImage.size, false, 0);
path.addClip()
originalImage.drawAtPoint(CGPointZero)
let maskedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return maskedImage;
}
当行:
localImage = maskImage(localImage!,
path: UIBezierPath(CGPath: CGPathCreateWithEllipseInRect(UIScreen.mainScreen().bounds, nil)))
被注释掉了,我看到了我的期望。
重新启动应用程序时,将下面的图片用作背景。
但是当它们存在时(未注释掉),我在重新启动应用程序时得到背景(当然在开始时拍摄相同的照片):
如果一切正常,鼠标应该出现在椭圆夹内,其大小与第一张图片相同(没有像现在那样放大)。