UISegmentedControl with Image and Title

后端 未结 6 2219
滥情空心
滥情空心 2020-12-15 13:45

I am using a UISegmentedControl inside a UIToolBar as button. I can\'t use a normal UIButtonBarItem, because I need to set the t

6条回答
  •  爱一瞬间的悲伤
    2020-12-15 14:32

    For Swift.

    segFont is the font for the embedded text.

    imageAlignment is the alignment of the image appearing left or right of the text.

    set imageAlignment to 0 for left alignment (image will appear to the left of the text) and 1 for right alignment (image will appear to the right of the text)

    class func textEmbededImage(image: UIImage, string: String, color:UIColor, imageAlignment: Int = 0, segFont: UIFont? = nil) -> UIImage {
    
    let font = segFont ?? UIFont.systemFontOfSize(16.0)
    
    let expectedTextSize: CGSize = (string as NSString).sizeWithAttributes([NSFontAttributeName: font])
    
    let width: CGFloat = expectedTextSize.width + image.size.width + 5.0
    
    let height: CGFloat = max(expectedTextSize.height, image.size.width)
    
    let size: CGSize = CGSizeMake(width, height)
    
    UIGraphicsBeginImageContextWithOptions(size, false, 0)
    
    let context: CGContextRef = UIGraphicsGetCurrentContext()!
    
    CGContextSetFillColorWithColor(context, color.CGColor)
    
    let fontTopPosition: CGFloat = (height - expectedTextSize.height) / 2.0
    
    let textOrigin: CGFloat = (imageAlignment == 0) ? image.size.width + 5 : 0
    let textPoint: CGPoint = CGPointMake(textOrigin, fontTopPosition)
    
    
    string.drawAtPoint(textPoint, withAttributes: [NSFontAttributeName: font])
    let flipVertical: CGAffineTransform = CGAffineTransformMake(1, 0, 0, -1, 0, size.height)
    CGContextConcatCTM(context, flipVertical)
    
    let alignment: CGFloat =  (imageAlignment == 0) ? 0.0 : expectedTextSize.width + 5.0
    CGContextDrawImage(context, CGRectMake(alignment, ((height - image.size.height) / 2.0), image.size.width, image.size.height), image.CGImage)
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    
    return newImage
    }
    

提交回复
热议问题