我正在尝试实现ios AR应用。我想做的是:如果用户触摸屏幕,则会发生屏幕截图,但是我只想将图像保存在正方形内并显示在左上角。因此,我需要裁剪屏幕截图。好像我传递了错误的正方形尺寸和位置?我究竟做错了什么?我是否使用了错误的坐标单位和大小单位?或者我是否在缩放比例?!
在此课程中,我将根据当前设备获得正方形的大小和位置
class ViewController: UIViewController, ARSKViewDelegate, UIPickerViewDataSource, UIPickerViewDelegate, SceneDelegate {
var squareRect: CGRect = CGRect(x: 0, y: 0, width: 0, height: 0)
@IBOutlet var sceneView: ARSKView!
//that's the square
@IBOutlet weak var squareImage: UIImageView!
//this is where the cropped image should be displayed
@IBOutlet weak var imageView: UIImageView!
...
func getRect() -> CGRect{
return squareRect
}
...
@objc func rotated(){
if UIDevice.current.orientation.isLandscape {
squareImage.frame.size.height = sceneView.frame.size.height * 0.77
squareImage.frame.size.width = squareImage.frame.size.height
}
else {
squareImage.frame.size.width = sceneView.frame.size.width * 0.77
squareImage.frame.size.height = squareImage.frame.size.width
}
squareImage.center = sceneView.center
squareRect = CGRect(origin: squareImage.frame.origin, size: squareImage.frame.size)
}
在本课程中,将处理触摸并显示裁剪的图像:
protocol SceneDelegate{
func getRect() -> CGRect
}
class Scene: SKScene {
var sceneDelegate: SceneDelegate?
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let sceneView = self. view as? ARSKView else{ return }
guard let imageView = sceneView.subviews.first as? UIImageView else { return }
if let image = UIImage(pixelBuffer: currentFrame.capturedImage) {
let cgImage: CGImage = CGImage(image)
let croppedCGImage = cgImage.cropping(to: self.sceneDelegate!.getRect())
let croppedImage = UIImage(cgImage: croppedCGImage!, scale: self.scale, orientation: up)
DispatchQueue.main.async {
imageView.image = croppedImage
}
注意:代码的基础是约旦·奥斯特伯格(Jordan Osterberg)在17年7月14日创建的(版权所有2017 Shadow Technology Systems)
所以this (click for image)是我的代码的作用:它会裁剪位于右上角的非常小的图片?
编辑:
您几乎看不到图像上的正方形,因此我上传了another image。箭头指向正方形的边缘。
很显然,我传递了错误的正方形尺寸和位置!但是为什么呢?
我将squareRect的大小和宽度替换为:
let heightInPixel = squareImage.frame.height * UIScreen.main.scale
let widthInPixel = squareImage.frame.width* UIScreen.main.scale
它现在实际上显示了更大的图像,但是仍然太小。 以及如何转换x和y位置?