在Swift中为图像添加阴影

时间:2019-05-23 22:58:35

标签: swift cocoa swiftocr

该项目来自garnele007,来自SwiftOCR。在Swift项目中有一个NSImage(也将其转换为.png进行保存),我想在其上面添加阴影。存在一些在viewcontroller等内部添加阴影的示例,但是到目前为止,我还没有一个如何使用诸如Core Graphics / Image之类的阴影添加阴影的示例。我的想象力给了我

randomImg.CGAddShadow(阴影:true,重量:中)

一些浮动说明使用了UIKit,但不适用于该MacOS项目。其他人则为了用户的利益而添加了一个临时层,但在保存阴影的情况下不保存文件。

当前代码如下:


            let customImage: (String) -> OCRImage = { code in
                let randomImg = randomImage()
                randomImg.lockFocus()

                randomImg.draw(in: CGRect(origin: CGPoint.zero, size: randomImg.size))


                NSString(string: code).draw(in: CGRect(origin: CGPoint(x: 0, y: -15.5 ), size: randomImg.size), withAttributes: randomFontAttributes())

                randomImg.unlockFocus()


                let data = NSBitmapImageRep(data: randomImg.tiffRepresentation!)?.representation(using: .png, properties: [:])

                 return randomImg
            }

希望最终结果是修改后的文件,上面有阴影,可以保存并稍后查看。

感谢任何建议

1 个答案:

答案 0 :(得分:0)

我最终使用的解决方案(随机棕褐色过滤器):


            let context = CIContext()

            // Load originalCIImage with contents of the URL
            var imageURL = Bundle.main.urlForImageResource(NSImage.Name(rawValue: "image.png"))
            var originalCIImage = CIImage(contentsOf: imageURL!)

            // Declare func for filter
            func sepiaFilter(_ input: CIImage, intensity: Double) -> CIImage?
            {
                let sepiaFilter = CIFilter(name:"CISepiaTone")
                sepiaFilter?.setValue(input, forKey: kCIInputImageKey)
                sepiaFilter?.setValue(intensity, forKey: kCIInputIntensityKey)
                return sepiaFilter?.outputImage
            }

            // call the filter func on the image
            let sepiaCIImage = sepiaFilter(originalCIImage!, intensity:0.9)

            // change the image from CIImage type to NSImage type
            let rep = NSCIImageRep(ciImage: sepiaCIImage!)
            let filteredImage = NSImage(size: rep.size)
            filteredImage.addRepresentation(rep)

            // change from NSImage type to .png format
            let filterData = NSBitmapImageRep(data: filteredImage.tiffRepresentation!)?.representation(using: .png, properties: [:])

            // save the png file to the desktop
            do {
                try filterData?.write(to: (FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask).first?.appendingPathComponent("FILTEREDIMAGE.png"))!)
            }
            catch _ {
                print("Adding filter to picture error")
            }

// END Sepia Filter