基本的想法是用不透明的顏色填充位圖上下文,然後清除我們想要剪切的任何東西。獲取該位圖上下文的圖像並用作掩碼。
import UIKit
// A couple of overlapping circles to play with
let frames = [
CGRect(x: 100, y: 100, width: 200, height: 200),
CGRect(x: 50, y: 50, width: 200, height: 200)
]
let blurView = UIImageView(image: ...) // <== You can drag an image here. Literals are cool.
let size = blurView.bounds.size
let scale = UIScreen.mainScreen().scale
// First, create a bitmap context to work in.
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedFirst.rawValue | CGBitmapInfo.ByteOrder32Little.rawValue)
let ctx = CGBitmapContextCreate(nil, Int(size.width*scale), Int(size.height*scale),
8, 4 * Int(size.width * scale), CGColorSpaceCreateDeviceRGB(), bitmapInfo.rawValue)
CGContextScaleCTM(ctx, scale, scale)
// iOS draws upsidedown from Core Graphics, so you'll probably want to flip your context:
CGContextConcatCTM(ctx, CGAffineTransformMake(1, 0, 0, -1, 0, size.height))
// Everything we want to draw should be opaque
// Everything we want to clip should be translucent
CGContextSetGrayFillColor(ctx, 1, 1) // white
CGContextFillRect(ctx, blurView.bounds)
// And now we clear all our circles
CGContextSetBlendMode(ctx, .Clear)
CGContextSetGrayFillColor(ctx, 1, 0) // clear
for f in frames {
CGContextFillEllipseInRect(ctx, f)
}
// Make the masking image
let maskImage = CGBitmapContextCreateImage(ctx)
// For your playground amusement (you can quicklook this line)
UIImage(CGImage: maskImage)
// Create the masking layer
let mask = CALayer()
mask.frame = blurView.layer.frame
mask.contents = maskImage
// And apply it
blurView.layer.mask = mask
// And the final so you can quicklook it
blurView
![enter image description here](https://i.stack.imgur.com/6eY5D.png)
也許你可以包括屏幕截圖:
,如果你喜歡,你可以複製到操場呢? – beyowulf