ios - Swift 3 以编程方式绘制 uiimage

标签 ios swift core-graphics

我没有 Core Graphics 的经验,但我需要绘制一个如下所示的动态 uiimage:

left

whole

(实际上我希望灰色区域清晰。所以红色看起来像 float 的)

这是我尝试过的代码:

public extension UIImage {

    public convenience init?(color: UIColor, size: CGSize = CGSize(width: 27, height: 5), isWhole: Bool = true) {
        let totalHeight: CGFloat = 5.0
        let topRectHeight: CGFloat = 1.0

        //if (isWhole) {
        let topRect = CGRect(origin: .zero, size: CGSize(width: size.width, height: topRectHeight))
        UIGraphicsBeginImageContextWithOptions(topRect.size, false, 0.0)
        color.setFill()
        UIRectFill(topRect)

        let bottomRect = CGRect(origin: CGPoint(x: 0, y: topRectHeight), size: CGSize(width: size.width, height: totalHeight - topRectHeight))
        UIGraphicsBeginImageContextWithOptions(bottomRect.size, false, 0.0)
        UIColor.blue.setFill()
        UIRectFill(bottomRect)

        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        guard let cgImage = image?.cgImage else { return nil }
        self.init(cgImage: cgImage)
    }

最佳答案

下面是一个示例,如果将 isWhole 属性设置为 false,则可以获取第一个图像;如果将其设置为 true,则可以获取第二个图像。您可以将此代码粘贴到 viewDidLoad 中来测试和使用它。

    var isWhole = false
    UIGraphicsBeginImageContextWithOptions(CGSize.init(width: 27, height: 5), false,0.0)
    var context = UIGraphicsGetCurrentContext()
    context?.setFillColor(UIColor.red.cgColor)
    if(context != nil){
        if(isWhole){
            context?.fill(CGRect(x: 0, y: 0, width: 27, height: 2.5))
        }
        else{
            context?.fill(CGRect(x: 0, y: 0, width: 13.5, height: 2.5))
        }
        context?.setFillColor(UIColor.gray.cgColor)
        context?.fill(CGRect(x: 0, y: 2.5, width: 27, height: 2.5))
    }


    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    var imageView = UIImageView(frame: CGRect(x: 100, y: 200, width: 27, height: 5))
    imageView.image = newImage
    self.view.addSubview(imageView)
    UIGraphicsEndImageContext()

如果您需要红色矩形具有圆角,只需将 fill(rect:CGRect) 更改为如下路径:

    if(isWhole){
        context?.addPath(CGPath(roundedRect: CGRect(x: 0, y: 0, width: 27, height: 2.5), cornerWidth: 1, cornerHeight: 1, transform: nil))
        context?.fillPath()
    }

关于ios - Swift 3 以编程方式绘制 uiimage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45015931/

相关文章:

ios - 如何创建 segue 或新的 View Controller 以显示在不同的 View Controller 上

iphone - cocos2d Sprite 帧缓存无法更改

iphone - CGContextFillEllipseInRect 行为怪异

iPhone iOS如何实例化一个黑白CGColorSpaceRef?

ios - 尽管使用较弱的委托(delegate)保留圈

IOS:使用dispatch_async的单元测试未执行

ios - 使用未解析的标识符 PFFacebookUtils

ios - 以编程方式连接 Storyboard w/ViewController

swift - Core Data 代码生成器如何决定是否将属性设为可选?

ios - iOS4 上未显示 CoreGraphics 渐变