使用CoreImage生成条纹线-没有尖锐的边缘

时间:2018-06-28 06:17:44

标签: ios swift core-image

我使用CoreImage框架使用带状线生成图像,并且输出似乎具有不正确的边缘,如下图所示。我使用的代码如下。

fileprivate func generateImage(_ width: CGFloat, _ height: CGFloat, withColor1: CIColor, withColor2: CIColor) -> CGImage? {

   let context = CIContext()

   if #available(iOS 10.0, *) {
   let stripes = CIFilter(name: "CIStripesGenerator", withInputParameters: [
                "inputColor0" : withColor2,
                "inputColor1" : withColor1,
                "inputWidth" : NSNumber(value: 10),
                "inputSharpness" : NSNumber(value: 0.7)

                ])!.outputImage!

    let rotate = CIFilter(name: "CIAffineTransform", withInputParameters: [ "inputImage" : stripes,"inputTransform" : NSValue(cgAffineTransform: CGAffineTransform(rotationAngle: -75.0))])!.outputImage!

    return context.createCGImage(rotate, from: CGRect(x: 0, y: 0, width: width, height: 50.0))!

        } else {
            // Fallback on earlier versions
        }

        return nil

    }

具有很高的清晰度

enter image description here

低清晰度(0.7)

enter image description here

我需要的是下面的

enter image description here

2 个答案:

答案 0 :(得分:6)

将弧度而不是度值赋予CGAffineTransform的rotationAngle:.em / -4 。

import UIKit
import CoreImage

fileprivate func
generateImage(_ width: CGFloat, _ height: CGFloat, withColor1: CIColor, withColor2: CIColor) -> CGImage? {

    let context = CIContext()

    let stripes = CIFilter(
        name: "CIStripesGenerator"
    ,   parameters: [
            "inputColor0"   : withColor2
        ,   "inputColor1"   : withColor1
        ,   "inputWidth"    : NSNumber( value: 10 )
        ,   "inputSharpness": NSNumber( value: 1 )
        ]
    )!.outputImage!

    let rotate = CIFilter(
        name: "CIAffineTransform"
    ,   parameters: [
            "inputImage"    : stripes
        ,   "inputTransform": NSValue( cgAffineTransform: CGAffineTransform( rotationAngle: .pi / -4 ) )
        ]
    )!.outputImage!

    return context.createCGImage( rotate, from: CGRect( x: 0, y: 0, width: width, height: height ) )!
}


class ViewController: UIViewController {
    @IBOutlet   weak    var oIV:    UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        oIV.image = UIImage(
            cgImage: generateImage(
                oIV.bounds.width
            ,   oIV.bounds.height
            ,   withColor1: CIColor( red:0, green:0, blue:0, alpha:1 )
            ,   withColor2: CIColor( red:1, green:1, blue:1, alpha:1 )
            )!
        )
    }
}

结果: enter image description here

答案 1 :(得分:3)

您可以尝试这样的操作,但是我没有对其进行正确的测试:

let generatedImage = generateImage(...)

let scaleX = yourView.frame.size.width / generatedImage.extent.size.width
let scaleY = yourView.frame.size.height / generatedImage.extent.size.height

let transformedImage = generatedImage.transformed(by: CGAffineTransform(scaleX: scaleX, y: scaleY))