之前筆者已經(jīng)分享過旋轉(zhuǎn)圖片的算法給大家了君躺,那接下來碰到的問題就是纬乍,當時只做了ImageView的旋轉(zhuǎn)跋选,旋轉(zhuǎn)一定角度之后谓苟,我該怎樣剪切最大的等比內(nèi)切矩形官脓?要解決的問題如下:
第一,怎樣旋轉(zhuǎn)畫布上的圖片
毫無疑問涝焙,我第一反應(yīng)就是使用CoreGraphics卑笨,初步的想法是將圖片畫在畫布上,然后和imageView做相同的仿射變換仑撞,但是大家都知道赤兴,CG的變換都是針對畫布的芭商,而不是圖片,那是不是就相當于畫布要和圖片做相反的動作搀缠?
第二铛楣,畫布大小
要保證剪切后的圖片和之前的圖像大小相同,那畫布的大小即圖片的大小
第三艺普,圖片的大小
大家應(yīng)該都知道簸州,系統(tǒng)在旋轉(zhuǎn)功能上不單單是旋轉(zhuǎn),還做了一定程度的縮放歧譬,需要我們重新計算旋轉(zhuǎn)之后的大小
圖片旋轉(zhuǎn)的倍數(shù)我是這樣計算的:
func imageViewScale() -> CGFloat {
let scaleX = self.imageView.frame.size.width/self.imageView.bounds.size.width
let scaleY = self.imageView.frame.size.height/self.imageView.bounds.size.height
let scale = fabsf(Float(scaleX)) > fabsf(Float(scaleY)) ? scaleX : scaleY
return scale
}
OK岸浑,那結(jié)合以上三點,我們總結(jié)代碼如下:
// 計算旋轉(zhuǎn)后圖片的大小
let size = CGSize(width: imageSize.width * self.imageViewScale(), height: imageSize.height * self.imageViewScale())
// 創(chuàng)建畫布
let context = CGContext.init(data: nil,
width: Int(imageSize.width),
height: Int(imageSize.height),
bitsPerComponent: sourceImage.bitsPerComponent,
bytesPerRow: 0,
space: sourceImage.colorSpace!,
bitmapInfo: sourceImage.bitmapInfo.rawValue)
context?.setFillColor(UIColor.clear.cgColor)
context?.fill(CGRect(origin: CGPoint.zero, size: imageSize))
context?.concatenate(transform.inverted())
context?.draw(sourceImage, in: CGRect(x: 0,
y: 0,
width: size.width,
height: size.height))
let result = context?.makeImage()
UIGraphicsEndImageContext()
坑還在后面瑰步。矢洲。上述代碼寫完之后發(fā)現(xiàn),圖片轉(zhuǎn)到圖像外面去了缩焦。读虏。。仔細看看角度好想對袁滥,但是盖桥,并不是圍繞圖片中心轉(zhuǎn)的,而是圍繞左上角轉(zhuǎn)動的题翻,Quartz2D就是這樣的揩徊。。嵌赠。塑荒。那如何解決呢,偶然google到一個前輩的分享姜挺,三步走齿税,如何走看下圖:
也就是說,先將畫布的anchorPoint向右向下移到中心位置初家,旋轉(zhuǎn)之后偎窘,再將畫布移回到原位置。
最終代碼如下:
// 計算旋轉(zhuǎn)后圖片的大小
let size = CGSize(width: imageSize.width * self.imageViewScale(), height: imageSize.height * self.imageViewScale())
// 創(chuàng)建畫布
let context = CGContext.init(data: nil,
width: Int(imageSize.width),
height: Int(imageSize.height),
bitsPerComponent: sourceImage.bitsPerComponent,
bytesPerRow: 0,
space: sourceImage.colorSpace!,
bitmapInfo: sourceImage.bitmapInfo.rawValue)
context?.setFillColor(UIColor.clear.cgColor)
context?.fill(CGRect(origin: CGPoint.zero, size: imageSize))
// quartz旋轉(zhuǎn)以左上角為中心溜在,so 將畫布移到右下角陌知,旋轉(zhuǎn)之后再向上移到原來位置
context?.translateBy(x: imageSize.width / 2, y: imageSize.height / 2)
context?.concatenate(transform.inverted())
context?.translateBy(x: -size.width / 2, y: -size.height / 2)
context?.draw(sourceImage, in: CGRect(x: 0,
y: 0,
width: size.width,
height: size.height))
let result = context?.makeImage()
UIGraphicsEndImageContext()
本文參考文章如下:
Quartz2D 圖像處理