【问题标题】:UIView.mask set the colorUIView.mask 设置颜色
【发布时间】:2017-05-04 17:06:59
【问题描述】:

我有一个 50 像素的方形 UIView,我将其设置为我的超级视图的掩码。

let squareView = UIView(frame...)

self.view.mask = squareView

结果是一个 50px 的正方形透明区域,但它周围的蒙版区域的颜色始终为白色。如何将透明方块周围蒙版区域的颜色更改为黑色?

 _______________
|               |    
|    <-------------- Masked area that I would like to change the color of
|               |
|      000000   |
|      000000 <-------- squareView: becomes transparent as expected
|      000000   |
|      000000   |
|               |
|               |
|               |
|_______________|

【问题讨论】:

  • 尝试将视图层的背景颜色设置为黑色self.view.layer.backgroundColor = UIColor.black.CGColor(输入注释...可能需要一些调整才能编译)
  • 这可能会有所帮助:stackoverflow.com/questions/29585943/…
  • @ScottThompson 谢谢,但是设置主视图的背景颜色对应用到它的蒙版颜色没有影响。在遮罩视图上设置背景颜色也没有效果。
  • @janusbalatbat 谢谢,但我在这篇文章中找不到与设置蒙版区域的背景颜色相关的任何内容。
  • 将使用的蒙版视图的唯一组件是 Alpha 通道。我建议你设置视图层的背景色,而不是视图的背景色。一个微妙但重要的区别。或许如果您展示更多代码,或者展示不良状态的图片,我们可以提供更多帮助。

标签: ios swift uiview calayer


【解决方案1】:

这是一个代码 sn-p,我认为它演示了您想要的效果。您应该能够将其粘贴到新的“单一视图”iOS 项目中,作为 Xcode 模板创建的视图控制器的 viewDidLoad() 方法。

我需要一些方法来设置遮罩视图的内容,而无需创建UIView 的子类(因为我很懒),所以我的示例创建了一个图像(其 alpha 通道大部分为 1.0,100x100 正方形透明 Alpha 通道)。我将其设置为遮罩视图的内容。

最后的计时器只是循环显示外部视图的一堆颜色,因为......这很有趣。

override func viewDidLoad() {
      super.viewDidLoad()
      self.view.backgroundColor = UIColor.blue

      let overallView = UIView(frame: CGRect(x:100, y:100, width:300, height:300))
      overallView.backgroundColor = UIColor.green

      // Draw a graphics with a mostly solid alpha channel
      // and a square of "clear" alpha in there.
      UIGraphicsBeginImageContext(overallView.bounds.size)
      let cgContext = UIGraphicsGetCurrentContext()
      cgContext?.setFillColor(UIColor.white.cgColor)
      cgContext?.fill(overallView.bounds)
      cgContext?.clear(CGRect(x:100, y:100, width: 100, height: 100))
      let maskImage = UIGraphicsGetImageFromCurrentImageContext()
      UIGraphicsEndImageContext()

      // Set the content of the mask view so that it uses our
      // alpha channel image
      let maskView = UIView(frame: overallView.bounds)
      maskView.layer.contents = maskImage?.cgImage
      overallView.mask = maskView

      self.view.addSubview(overallView)

      var hue = CGFloat(0)
      Timer.scheduledTimer(withTimeInterval: 0.2, repeats: true) {
          (_) in
          let color = UIColor(hue: hue, saturation: 1.0, brightness: 1.0, alpha: 1.0)
          hue = hue + (1.0/20);
          if hue >= 1.0 { hue = 0 }

          overallView.backgroundColor = color
      }
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-27
    • 2020-08-09
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-21
    相关资源
    最近更新 更多