hi i am a beginner in speed writing I refer to this writing method and apply it in my segment controller I am using swift 5.7 method This can be successfully used and executed with
But i have a problem that i can't change the color of my text and icon I try to add something in "string.draw" but it dosen't work
The method I use is as follows
class func textEmbededImage(image: UIImage, string: String, color: UIColor, imageAlignment: Int = 0) -> UIImage {
let font = UIFont.systemFont(ofSize: 13.0)
let expectedTextSize: CGSize = (string as NSString).size(withAttributes: [NSAttributedString.Key.font: font])
let width: CGFloat = expectedTextSize.width + image.size.width + 5.0
let height: CGFloat = max(expectedTextSize.height, image.size.width)
let size: CGSize = CGSize(width: width, height: height)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
let context: CGContext = UIGraphicsGetCurrentContext()!
context.setFillColor(color.cgColor)
let fontTopPosition: CGFloat = (height - expectedTextSize.height) / 2.0
let textOrigin: CGFloat = (imageAlignment == 0) ? image.size.width + 5 : 0
let textPoint: CGPoint = CGPoint.init(x: textOrigin, y: fontTopPosition)
string.draw(at: textPoint, withAttributes: [.font : font , .foregroundColor : UIColor.gray])
let flipVertical: CGAffineTransform = CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: size.height)
context.concatenate(flipVertical)
let alignment: CGFloat = (imageAlignment == 0) ? 0.0 : expectedTextSize.width + 5.0
context.draw(image.cgImage!, in: CGRect.init(x: alignment, y: ((height - image.size.height) / 2.0), width: image.size.width, height: image.size.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext(
return newImage!
}
and i use like this
customSegment.setImage(UIImage.textEmbededImage(image: UIImage.add, string: "QQQ", color: .red),forSegmentAt: 0)
customSegment.setImage(UIImage.textEmbededImage(image: UIImage.add, string: "AAA", color: .white),forSegmentAt: 1)
customSegment.setImage(UIImage.textEmbededImage(image: UIImage.add, string: "BBB", color: .red),forSegmentAt: 2)
but this doesn't work for I went into debug view hierarchy xcode to try to find the problem debug view hierarchy But what puzzles me even more is that what I see on the right layer is the gray color I set, but what I see on the screen is the blue color set by the system
How can I solve it
In addition, I also want to ask, how to make different text colors to achieve the effect when selecting