尝试实现如下图所示的内容。图像具有掩模以显示图像的某些部分。这是创建形状的代码
let shape = CAShapeLayer()
shape.opacity = 0.5
shape.lineWidth = 2
shape.lineJoin = kCALineJoinMiter
let path = UIBezierPath()
path.moveToPoint(CGPointMake(0 , 0))
path.addLineToPoint(CGPointMake(200, 0))
path.addLineToPoint(CGPointMake(160, 200))
path.addLineToPoint(CGPointMake(0, 200))
path.closePath()
shape.path = path.CGPath
有没有办法将图像添加到此图层中。所以它的界限分别设置为形状?之前/之后图像可以忽略。
任何线索都会受到赞赏。谢谢!
答案 0 :(得分:0)
这是我提出的解决方案。你需要有适当的掩码图像。
import UIKit
import SnapKit
class TestScreenController: UIViewController {
let beforeView = UIImageView()
let afterView = UIImageView()
let maskView = UIImageView()
let divider = UIImageView(image: UIImage(named: "before_after_image"))
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
setup()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setup(){
self.view.addSubview(maskView)
self.maskView.addSubview(beforeView)
self.maskView.addSubview(afterView)
self.maskView.addSubview(divider)
maskView.snp_makeConstraints { (make) in
make.top.equalTo(self.view).offset(50)
make.width.equalTo(300)
make.height.equalTo(110)
make.centerX.equalTo(self.view)
}
maskView.layer.cornerRadius = 15
maskView.layer.masksToBounds = true
let image = UIImage(named: "beforeWash-min.png")
let maskingImage = UIImage(named: "beforeImageM-1")
beforeView.image = maskImage(image!, mask: maskingImage!)
beforeView.contentMode = .ScaleToFill
beforeView.snp_makeConstraints { (make) in
make.top.left.height.equalTo(self.maskView)
make.width.equalTo(self.maskView).multipliedBy(0.50).offset(12)
}
let imageA = UIImage(named: "afterWash-min.png")
let maskingImageA = UIImage(named: "afterImageM-1")
afterView.image = maskImage(imageA!, mask: maskingImageA!)
afterView.contentMode = .ScaleToFill
afterView.snp_makeConstraints { (make) in
make.top.right.height.equalTo(self.maskView)
make.width.equalTo(self.maskView).multipliedBy(0.50).offset(10)
}
divider.snp_makeConstraints { (make) in
make.center.equalTo(maskView)
make.height.equalTo(maskView)
}
}
func maskImage(image:UIImage, mask:(UIImage))->UIImage{
let imageReference = image.CGImage
let maskReference = mask.CGImage
let imageMask = CGImageMaskCreate(CGImageGetWidth(maskReference),
CGImageGetHeight(maskReference),
CGImageGetBitsPerComponent(maskReference),
CGImageGetBitsPerPixel(maskReference),
CGImageGetBytesPerRow(maskReference),
CGImageGetDataProvider(maskReference), nil, true)
let maskedReference = CGImageCreateWithMask(imageReference, imageMask)
let maskedImage = UIImage(CGImage:maskedReference!)
return maskedImage
}
}