私がテスト用に使用しているアプリは、写真を撮って 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)))
コメントアウトされていますが、私が期待していることがわかります。
下の写真をサックして、アプリを再起動するときに背景として使用します。
しかし、それらが存在する場合(コメントアウトされていない場合)、アプリを再起動すると背景が表示されます(もちろん、開始時に同じ写真を撮ります):
正常に動作した場合、マウスは最初の画像と同じサイズで楕円形のクリップ内に表示されます (現在のように拡大されていません)。