有人可以通过附加图片和标题(两者)来帮助我实现segmentedViewController。图像在顶部,标题位于图像底部的快速语言中。我已经通过staackoverflow并且可以在目标C中找到解决方案。而将其转换为Swift我已经坚持以下目标-c语句
CGContextDrawImage(context,(CGRect){{0,(height - image.size.height)/ 2},{image.size.width,image.size.height}},[image CGImage]);
我关注的链接:UISegmentedControl with Image and Title
我的Swift转换代码:
扩展UIImage {
public func textEmbededImage(image: UIImage, string: String, color:UIColor) -> UIImage {
let font = 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 textPoint: CGPoint = CGPointMake(image.size.width + 5, fontTopPosition)
(string as NSString).drawAtPoint(textPoint, withAttributes: [NSFontAttributeName: font])
let flipVertical: CGAffineTransform = CGAffineTransformMake(1, 0, 0, -1, 0, size.height)
CGContextConcatCTM(context, flipVertical)
//I am stuck here.. please help me on it.
//Images upside down so flip them
return image
}
答案 0 :(得分:0)
segFont是嵌入文本的字体,imageAlignment是文本左侧或右侧出现的图像的对齐方式。
将imageAlignment设置为0
以进行左对齐(图像将显示在文本的左侧),1
用于右对齐(图像将显示在文本的右侧)
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
}
希望这可以帮助将来需要它的人。
答案 1 :(得分:0)
这可以预期现在在iOS 12和黑暗与光明模式下,色彩会重新着色图像。我有一个蓝点图像,现在仅呈现为黑色。