CALayer带有透明孔

ani*_*hin 104 objective-c calayer ios quartz-core

我有一个简单的视图(图片的左侧),我需要创建一些覆盖(图片的右侧)到这个视图.这个叠加应该有一些不透明度,所以下面的视图仍然是部分可见的.最重要的是,这个叠加层应该在它的中间有一个圆孔,所以它不会覆盖视图的中心(见下图).

我可以轻松创建一个这样的圆圈:

int radius = 20; //whatever
CAShapeLayer *circle = [CAShapeLayer layer];

circle.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0,radius,radius) cornerRadius:radius].CGPath;
circle.position = CGPointMake(CGRectGetMidX(view.frame)-radius,
                              CGRectGetMidY(view.frame)-radius);
circle.fillColor = [UIColor clearColor].CGColor;
Run Code Online (Sandbox Code Playgroud)

像这样的"完整"矩形覆盖:

CAShapeLayer *shadow = [CAShapeLayer layer];
shadow.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, view.bounds.size.width, view.bounds.size.height) cornerRadius:0].CGPath;
shadow.position = CGPointMake(0, 0);
shadow.fillColor = [UIColor grayColor].CGColor;
shadow.lineWidth = 0;
shadow.opacity = 0.5;
[view.layer addSublayer:shadow];
Run Code Online (Sandbox Code Playgroud)

但我不知道如何将这两个层组合在一起,以便创建我想要的效果.任何人?我已经尝试了所有的东西......非常感谢你的帮助!

图片

ani*_*hin 201

我能够用Jon Steinmetz的建议解决这个问题.如果有人关心,这是最终的解决方案:

int radius = myRect.size.width;
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, self.mapView.bounds.size.width, self.mapView.bounds.size.height) cornerRadius:0];
UIBezierPath *circlePath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, 2.0*radius, 2.0*radius) cornerRadius:radius];
[path appendPath:circlePath];
[path setUsesEvenOddFillRule:YES];

CAShapeLayer *fillLayer = [CAShapeLayer layer];
fillLayer.path = path.CGPath;
fillLayer.fillRule = kCAFillRuleEvenOdd;
fillLayer.fillColor = [UIColor grayColor].CGColor;
fillLayer.opacity = 0.5;
[view.layer addSublayer:fillLayer];
Run Code Online (Sandbox Code Playgroud)

对于Swift 3.x:

let radius = myRect.size.width
let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: self.mapView.bounds.size.width, height: self.mapView.bounds.size.height), cornerRadius: 0)
let circlePath = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: 2 * radius, height: 2 * radius), cornerRadius: radius)
path.append(circlePath)
path.usesEvenOddFillRule = true

let fillLayer = CAShapeLayer()
fillLayer.path = path.cgPath
fillLayer.fillRule = kCAFillRuleEvenOdd
fillLayer.fillColor = Color.background.cgColor
fillLayer.opacity = 0.5
view.layer.addSublayer(fillLayer)
Run Code Online (Sandbox Code Playgroud)

  • 它甚至可以在两年后帮助!! 谢谢 :) (7认同)
  • 为了增加灵活性,请将视图子类设为"IBDesignable".这真的很容易!要开始,请将上面的代码插入到我对此问题的回答中:http://stackoverflow.com/questions/14141081/uiview-drawrect-draw-the-inverted-pixels-make-a-hole-a-window阴性空间/ 31255084#31255084 (2认同)
  • 作为一个iOS新手开发人员,我花了几个小时来弄清楚为什么这段代码会产生奇怪的结果。最终我发现,如果在某个时候重新计算了覆盖蒙版,则必须删除添加的子层。这可以通过view.layer.sublayers属性来实现。非常感谢您的回答! (2认同)

Nic*_*Yap 29

为了创建这种效果,我发现最简单的方法是创建一个覆盖屏幕的整个视图,然后使用图层和UIBezierPaths减去部分屏幕.对于Swift实现:

// Create a view filling the screen.
let overlay = UIView(frame: CGRectMake(0, 0, 
    UIScreen.mainScreen().bounds.width,
    UIScreen.mainScreen().bounds.height))

// Set a semi-transparent, black background.
overlay.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.85)

// Create the initial layer from the view bounds.
let maskLayer = CAShapeLayer()
maskLayer.frame = overlay.bounds
maskLayer.fillColor = UIColor.blackColor().CGColor

// Create the frame for the circle.
let radius: CGFloat = 50.0
let rect = CGRectMake(
        CGRectGetMidX(overlay.frame) - radius,
        CGRectGetMidY(overlay.frame) - radius,
        2 * radius,
        2 * radius)

// Create the path.
let path = UIBezierPath(rect: overlay.bounds)
maskLayer.fillRule = kCAFillRuleEvenOdd

// Append the circle to the path so that it is subtracted.
path.appendPath(UIBezierPath(ovalInRect: rect))
maskLayer.path = path.CGPath

// Set the mask of the view.
overlay.layer.mask = maskLayer

// Add the view so it is visible.
self.view.addSubview(overlay)
Run Code Online (Sandbox Code Playgroud)

我测试了上面的代码,结果如下:

在此输入图像描述

我向CocoaPods添加了一个库,它抽象了很多上面的代码,并允许您轻松创建带有矩形/圆形孔的叠加层,允许用户与叠加层后面的视图进行交互.我用它为我们的一个应用程序创建了这个教程:

使用TAOverlayView的教程

该库名为TAOverlayView,在Apache 2.0下是开源的.希望对你有帮助!

  • 不错的更新,尼克.我在你的角落 - 我自己已经发布了库和实用程序,我知道当我的文档已经涵盖它时,在这里提供完整的答案似乎是多余的...但是我的想法是保持答案是自足的尽可能.而且,除了垃圾邮件外,其他人都没有发帖,所以我宁愿不与他们混在一起.我假设你有同样的想法,这就是我向你指出的原因.干杯! (3认同)

Ran*_*ndy 11

接受的解决方案Swift 3.0兼容

let radius = myRect.size.width
let path = UIBezierPath(roundedRect: CGRect(x: 0.0, y: 0.0, width: self.mapView.bounds.size.width, height: self.mapView.bounds.size.height), cornerRadius: 0)
let circlePath = UIBezierPath(roundedRect: CGRect(x: 0.0, y: 0.0, width: 2.0*radius, height: 2.0*radius), cornerRadius: radius)
path.append(circlePath)
path.usesEvenOddFillRule = true

let fillLayer = CAShapeLayer()
fillLayer.path = path.cgPath
fillLayer.fillRule = kCAFillRuleEvenOdd
fillLayer.fillColor = UIColor.gray.cgColor
fillLayer.opacity = 0.5
view.layer.addSublayer(fillLayer)
Run Code Online (Sandbox Code Playgroud)


skw*_*hua 10

我采用了与animal_chin类似的方法,但我更具视觉效果,因此我使用插座和自动布局在Interface Builder中设置了大部分内容.

这是我在Swift中的解决方案

    //shadowView is a UIView of what I want to be "solid"
    var outerPath = UIBezierPath(rect: shadowView.frame)

    //croppingView is a subview of shadowView that is laid out in interface builder using auto layout
    //croppingView is hidden.
    var circlePath = UIBezierPath(ovalInRect: croppingView.frame)
    outerPath.usesEvenOddFillRule = true
    outerPath.appendPath(circlePath)

    var maskLayer = CAShapeLayer()
    maskLayer.path = outerPath.CGPath
    maskLayer.fillRule = kCAFillRuleEvenOdd
    maskLayer.fillColor = UIColor.whiteColor().CGColor

    shadowView.layer.mask = maskLayer
Run Code Online (Sandbox Code Playgroud)


Luc*_*nzo 7

Code Swift 2.0兼容

从@animal_inch回答开始,我编写了一个小实用程序类,希望它会欣赏:

import Foundation
import UIKit
import CoreGraphics

/// Apply a circle mask on a target view. You can customize radius, color and opacity of the mask.
class CircleMaskView {

    private var fillLayer = CAShapeLayer()
    var target: UIView?

    var fillColor: UIColor = UIColor.grayColor() {
        didSet {
            self.fillLayer.fillColor = self.fillColor.CGColor
        }
    }

    var radius: CGFloat? {
        didSet {
            self.draw()
        }
    }

    var opacity: Float = 0.5 {
        didSet {
           self.fillLayer.opacity = self.opacity
        }
    }

    /**
    Constructor

    - parameter drawIn: target view

    - returns: object instance
    */
    init(drawIn: UIView) {
        self.target = drawIn
    }

    /**
    Draw a circle mask on target view
    */
    func draw() {
        guard (let target = target) else {
            print("target is nil")
            return
        }

        var rad: CGFloat = 0
        let size = target.frame.size
        if let r = self.radius {
            rad = r
        } else {
            rad = min(size.height, size.width)
        }

        let path = UIBezierPath(roundedRect: CGRectMake(0, 0, size.width, size.height), cornerRadius: 0.0)
        let circlePath = UIBezierPath(roundedRect: CGRectMake(size.width / 2.0 - rad / 2.0, 0, rad, rad), cornerRadius: rad)
        path.appendPath(circlePath)
        path.usesEvenOddFillRule = true

        fillLayer.path = path.CGPath
        fillLayer.fillRule = kCAFillRuleEvenOdd
        fillLayer.fillColor = self.fillColor.CGColor
        fillLayer.opacity = self.opacity
        self.target.layer.addSublayer(fillLayer)
    }

    /**
    Remove circle mask
    */


  func remove() {
        self.fillLayer.removeFromSuperlayer()
    }

}
Run Code Online (Sandbox Code Playgroud)

然后,在你的代码中的任何地方:

let circle = CircleMaskView(drawIn: <target_view>)
circle.opacity = 0.7
circle.draw()
Run Code Online (Sandbox Code Playgroud)