1
我想從scrollView抓取當前縮放圖像,將其裁剪到當前幀,將其更改爲黑白,然後重新顯示裁剪後的圖像以黑色和白色滾動查看。從UIScrollView抓取當前圖像,轉換成黑白圖像,然後回滾到滾動視圖
當我在下面運行我的代碼(來自buttonAction)後,scrollView似乎沒有顯示任何東西,但我仍然可以滾動並放大不存在的圖像。沒有編譯錯誤/警告或seg故障。
任何想法,我哪裏出錯了?
func grabImageFromCurrentView() -> UIImage {
// grab image from current zoom
// Note: "CIImage(image: imageToChange)" fails later on if the "false" here is set to true
// it has something to do with setting the image to RGBA instead of RGB
UIGraphicsBeginImageContextWithOptions(scrollView.bounds.size, false, UIScreen.mainScreen().scale)
let offset = scrollView.contentOffset
CGContextTranslateCTM(UIGraphicsGetCurrentContext(), -offset.x, -offset.y)
scrollView.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
// turn image to black and white image
func setNoirFilter(imageToChange: UIImage) -> UIImage {
let originalFrameImage = CIImage(image: imageToChange)
let filter = CIFilter(name: "CIPhotoEffectNoir")
filter?.setDefaults()
filter?.setValue(originalFrameImage, forKey: kCIInputImageKey)
let imageOutput = filter!.outputImage
let image = UIImage(CIImage: imageOutput!)
return image
}
func displayImage(image: UIImage) {
let originalImage = image
imageView.image = originalImage
imageView.contentMode = UIViewContentMode.Center
imageView.frame = CGRectMake(0,0, originalImage.size.width, originalImage.size.height)
scrollView.contentSize = originalImage.size
let scrollViewFrame = scrollView.frame
let scaleWidth = scrollViewFrame.size.width/scrollView.contentSize.width
let scaleHeight = scrollViewFrame.size.height/scrollView.contentSize.height
let minScale = min(scaleHeight, scaleWidth)
scrollView.minimumZoomScale = minScale
scrollView.maximumZoomScale = 50 // set so high for high resolution images I'll be using
scrollView.zoomScale = minScale
centerScrollViewContents()
}
@IBAction func buttonAction(sender: UIButton) {
let currentViewImage = grabImageFromCurrentView()
let blackAndWhiteImage = setNoirFilter(currentViewImage)
displayImage(blackAndWhiteImage)
}
嘗試使用一些斷點來查看它出錯的位置。 – Koen