以编程方式创建通用矢量图像

时间:2016-01-03 12:57:32

标签: ios swift vector uiimage universal

我们现在可以在Xcode中创建通用矢量图像,方法是将它们添加到图像资源文件夹中,然后将比例因子更改为单个矢量。我想知道如何以编程方式执行此操作。我尝试过以下但没有运气:(

func resizeImage(image: UIImage, newSize: CGSize) -> (UIImage) {
    let newRect = CGRectIntegral(CGRectMake(0,0, newSize.width, newSize.height))
    let imageRef = image.CGImage

    let scaleFactor = UIScreen.mainScreen().scale

    UIGraphicsBeginImageContextWithOptions(newSize, false, scaleFactor)

  //  UIGraphicsBeginImageContextWithOptions(newSize, false, 0.5)
    let context = UIGraphicsGetCurrentContext()

    // Set the quality level to use when rescaling

    CGContextSetInterpolationQuality(context, CGInterpolationQuality.High)


    let flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, newSize.height)

    CGContextConcatCTM(context, flipVertical)
    // Draw into the context; this scales the image
    CGContextDrawImage(context, newRect, imageRef)

    let newImageRef = CGBitmapContextCreateImage(context)! as CGImage
    let newImage = UIImage(CGImage: newImageRef)

    // Get the resized image from the context and a UIImage
    UIGraphicsEndImageContext()

    return newImage

}

1 个答案:

答案 0 :(得分:1)

这应该这样做。是的...... Apple通过勾选保存矢量数据,将其设置在故事板中。我不确定如何以编程方式保存矢量数据。

    public class var add: UIImage {
    let path = bundle.url(forResource: "plusReal", withExtension: "pdf")
    return drawPDFFromURL(url: path!)!
}

class func drawPDFFromURL(url: URL) -> UIImage? {
      guard let document = CGPDFDocument(url as CFURL),
            let page = document.page(at: 1) else {return nil }
    let pageRect = page.getBoxRect(.mediaBox)
    let renderer = UIGraphicsImageRenderer(size: pageRect.size)

    let img = renderer.image { ctx in
        UIColor.white.set()
        ctx.fill(pageRect)
        ctx.cgContext.translateBy(x: 0.0, y: pageRect.size.height)
        ctx.cgContext.scaleBy(x: 1.0, y: -1.0)
        ctx.cgContext.drawPDFPage(page)
    }
    return img
}