1
我發現CGImage.cropping(to:)
將使用左上角的原點(增加Y向下)而不是左下角(隨着Y向上增加)處理指定的矩形, 。這是特別奇怪的,因爲CGImage
默認情況下不是這樣定向的,因爲在應用掩碼時情況並非如此。請注意,這與UIImage
和方向無關 - 這是OS X特定的。CGImage.cropping(to :)在OS X上翻轉
我將此作爲一個問題提交,但這更多的是一個觀察。 Core Graphics上的Stack Overflow上的iOS中有更多的信息比OS X更多,Apple的裁剪文檔沒有解釋這一點。
下面是繪製圖像右下象限的代碼,而期望它繪製右上象限。
func getImage(_ url: CFURL) -> CGImage? {
guard let imageSource = CGImageSourceCreateWithURL(url, nil) else { return nil }
guard let image = CGImageSourceCreateImageAtIndex(imageSource, 0, nil) else {
let imageSourceStatus = CGImageSourceGetStatus(imageSource)
Swift.print("image nil, Image Source Status = \(imageSourceStatus)")
return nil
}
return image
}
func northeastQuadrant(fromImage: CGImage) -> CGRect {
let w = CGFloat(fromImage.width)
let h = CGFloat(fromImage.height)
let bottomleft = CGPoint(x: w/2.0, y: h/2.0)
return CGRect(x: bottomleft.x, y: bottomleft.y, width: w/2.0, height: h/2.0)
}
func southwestQuadrant(fromImage: CGImage) -> CGRect {
let w = CGFloat(fromImage.width)
let h = CGFloat(fromImage.height)
return CGRect(x: 0, y: 0, width: w/2.0, height: h/2.0)
}
class CGImageView: NSView {
func setImage() {
let url = CFURLCreateWithString(nil, "file:////Users/erickampman/Documents/FractIFS/Demonic%20Scarecrows.tiff" as CFString, nil)
let img = getImage(url!)
let quad = northeastQuadrant(fromImage: img!)
// let quad = southwestQuadrant(fromImage: img!)
image = img!.cropping(to: quad)
}
override func draw(_ dirtyRect: NSRect) {
if nil == image {
Swift.print("Calling setImage")
setImage()
}
guard let image = self.image else {
Swift.print("Nil image!")
return
}
super.draw(dirtyRect)
guard let cgContext = NSGraphicsContext.current?.cgContext else { return }
Swift.print("ctx transform: \(cgContext.ctm)")
cgContext.saveGState();
cgContext.draw(image, in: self.bounds, byTiling: false)
cgContext.restoreGState();
}
var image: CGImage?
}