ios - 绘制像素化线

标签 ios uikit core-graphics uibezierpath cashapelayer

我正在尝试绘制看起来像这种风格的“像素化”或“矢量化”线条:
enter image description here
enter image description here

理想情况下,我试图通过 CAShapeLayer 之类的东西绘制路径,并将路径像素化为这种风格。它不需要像实际 Assets 那样看起来 super 棒,但它需要遵循一般风格。我已经尝试了几种方法,并且非常接近,结果在这里是正确的:
enter image description here

我现在唯一的问题是消除应用于我尝试这样做的方式的模糊。我需要将我的结果像素化但仍然非常清晰,这是我最近用来获得上述效果的方法:

let path = UIBezierPath(roundedRect: bounds, cornerRadius: 20)
let lay = CAShapeLayer()
lay.path = path.cgPath
lay.strokeColor = UIColor.green_bright.cgColor
lay.lineWidth = 5
lay.fillColor = nil
lay.shouldRasterize = true
lay.rasterizationScale = 0.1
layer.addSublayer(lay)

我也尝试使用 CIPixellate 之类的 CIFilter,但无法弄清楚如何以任何方式将这样的过滤器应用于 CAShapeLayer 或路径。

有没有办法清理这种方法或任何其他方式来实现这种效果?感谢所有反馈或想法。

更新:我试图通过将我的图层变成图像并应用 CIFilter 来使用过滤器,这是我尝试失败的方式:
extension CAShapeLayer {
    func apply(_ filter: String) -> UIImage? {
        let context = CIContext(options: nil)
        let renderer = UIGraphicsImageRenderer(size: frame.size)
        if let currentFilter = CIFilter(name: filter) {
            let image = renderer.image { context in
                render(in: context.cgContext)
            }
            let beginImage = CIImage(image: image)
            currentFilter.setValue(beginImage, forKey: kCIInputImageKey)

            if let output = currentFilter.outputImage {
                if let cgimg = context.createCGImage(output, from: output.extent) {
                    return UIImage(cgImage: cgimg)
                }
            }
        }
        return nil
    }
}

最佳答案

如果这就是你的意思...

enter image description here

...那么我认为您使用 CIPixellate CIFilter 的想法是正确的,因为这就是我获得该图像的方式。步骤是:

  • 使用形状图层构建您的形状,基本上就像您已经在做的那样。
  • 制作图形图像上下文并将形状图层渲染到其中。现在你已经从形状层制作了一个 UIImage。
  • 将 UIImage 制作成 CIImage 并将其通过 CIPixellate 过滤器。
  • 再次制作图形图像上下文;在过滤器的 CIImage 输出周围包裹一个 UIImage 并将其绘制到图像上下文中。现在您已将过滤器输出渲染为新的像素化 UIImage。
  • 显示生成的 UIImage。
  • 关于ios - 绘制像素化线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60368363/

    相关文章:

    cocoa-touch - 绘制圆并存储在 UIImage 中

    ios - 将两个 UIView 合并为一个 UIImage

    ios - 在drawrect方法中翻转CGContext会绘制在错误的位置

    iphone - 无法在 ios 中创建 sqlite3 数据库

    ios - 在按钮上按下 segue 不起作用

    ios - backgroundView 的慢速模式绘制

    ios - UIBarButton 渲染问题

    iphone - UIControlEventTouchDragOutside 和 UIControlEventTouchDragExit 之间的区别在哪里?

    ios - ITMS-90809:不推荐使用的API使用错误苹果将停止接受使用UIWebView API的应用程序的提交。

    ios - 什么时候应该使用 __bridge 与 CFBridgingRelease/CFBridgingRetain?