Text color in the HUD - ios

Here is my code:
override func draw(_ rect: CGRect) {
let boxWidth: CGFloat = 96
let boxHeight: CGFloat = 96
let boxRect = CGRect(x: round((bounds.size.width - boxWidth) / 2),
y: round((bounds.size.height - boxHeight) / 2),
width: boxWidth, height: boxHeight)
let roundedRect = UIBezierPath(roundedRect: boxRect, cornerRadius: 10)
UIColor(white: 0.3, alpha: 0.8).setFill()
roundedRect.fill()
if let image = UIImage(named: "Checkmark") {
let imagePoint = CGPoint(
x: center.x - round(image.size.width / 2),
y: center.y - round(image.size.height / 2) - boxHeight / 8)
image.draw(at: imagePoint)
}
let attribs = [ kCTFontAttributeName: UIFont.systemFont(ofSize: 66.0), kCTForegroundColorAttributeName: UIColor.white]
let textSize = text.size(withAttributes: attribs as [NSAttributedString.Key : Any])
let textPoint = CGPoint(
x: center.x - round(textSize.width / 2),
y: center.y - round(textSize.height / 2) + boxHeight / 4)
text.draw(at: textPoint, withAttributes: attribs as [NSAttributedString.Key : Any])
}
The text color in the HUD is black. Why and how can I change it to white ?

You should use NSAttributedString.Key instead of CoreText keys try to replace this:
let attribs = [ kCTFontAttributeName: UIFont.systemFont(ofSize: 66.0), kCTForegroundColorAttributeName: UIColor.white]
with this:
let attribs: [NSAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: 66.0),
.foregroundColor: UIColor.green]

You can change it on this line
let attribs = [ kCTFontAttributeName: UIFont.systemFont(ofSize: 66.0), kCTForegroundColorAttributeName: UIColor.white.CGColor]
The foreground color of the text to which this attribute applies. The value associated with this attribute must be a CGColor object. Default value is black. Refer here

Try this:
let attribs = [NSAttributedString.Key.font.rawValue: UIFont.systemFont(ofSize: 66.0), NSAttributedString.Key.foregroundColor: UIColor.white] as! [String : Any]

Related

Position CGRect in the center for text output

So I have the following code:
let number = cluster.memberAnnotations.count
displayPriority = .defaultHigh
image = textToImage(
drawText: "\(number)",
inImage: UIImage(named: "map-pin-full-cluster-1")!
.withTintColor(.blue, renderingMode: . alwaysTemplate)
.resizeWith(
newSize: CGSize(width: 35, height: 35)), atPoint: CGPointMake(14.5, 3.5)
)
Which outputs the following look on the map:
Here is a function that I am using to assist me:
func textToImage(drawText text: String, inImage image: UIImage, atPoint point: CGPoint) -> UIImage {
let textColor = UIColor.white
let textFont = UIFont(name: "Helvetica Bold", size: 12)!
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(image.size, false, scale)
let textFontAttributes = [
NSAttributedString.Key.font: textFont,
NSAttributedString.Key.foregroundColor: textColor,
] as [NSAttributedString.Key : Any]
image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))
let rect = CGRect(origin: point, size: image.size)
text.draw(in: rect, withAttributes: textFontAttributes)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
Problem:
When the number ends up going into double digit, it isn't contained within the circle, how can I format my code so that I can center a number based on a CRect or other call?
:
Got it working thanks to #Larme's guidance:
let paragraph = NSMutableParagraphStyle()
paragraph.alignment = .center
let textFontAttributes = [
NSAttributedString.Key.font: textFont,
NSAttributedString.Key.foregroundColor: textColor,
NSAttributedString.Key.paragraphStyle: paragraph,
] as [NSAttributedString.Key : Any]
image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))
Define a NSMutableParagraphStyle() and set the paragraphStyle to it's attribute.

string print table format dynamically in swift

I am new in Receipt concept in swift. I want to print receipt like below image.
https://i.stack.imgur.com/ZB4bV.jpg
My Code:
let result = formattedString(left: "MAXIS Hotlink", right: "25.00",left1: "1")
+ "\n" + formattedString(left:"DIGI Prepaid", right: "5.00",left1: "0")
+ "\n" + formattedString(left:"CELCOM Xpax", right: "5.00",left1: "2")
print(result)
func formattedString(left: String, right: String,left1: String, width: Int = 20) -> String {
// The `max` call returns 0 if `width - left.count` is negative
let filler = String(repeating: " ", count: max(0, width - left.count))
return left + filler + right + filler + left1
}
But receipt not properly aligned when length increased. I want to print the string like below imagetype. Please anybody help me
if you want to print the receipt in the image, formatted string is not a good solution. Instead, you should have a template jpg. Then, you should draw information over the template. In this case, you can use a blank jpg file with a relevant size to have a receipt.
For example;
func getReceipt() -> UIImage? {
guard let image = UIImage(named: "receipt.jpg") else {return nil}
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(image.size, false, scale)
let toFromFontAttributes = [
NSAttributedString.Key.font: UIFont(name: "HelveticaNeue-Thin", size: 16.0)!,
NSAttributedString.Key.foregroundColor: UIColor.black
] as [NSAttributedString.Key: Any]
let subjectMessageAttributes = [
NSAttributedString.Key.font: UIFont(name: "HelveticaNeue-Thin", size: 16.0)!,
NSAttributedString.Key.foregroundColor: UIColor.black
] as [NSAttributedString.Key: Any]
image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))
let itemRect = CGRect(origin: CGPoint(x: 50, y: 50), size: image.size)
let itemText = "item"
itemText.draw(in: itemRect, withAttributes: toFromFontAttributes)
let quantityRect = CGRect(origin: CGPoint(x: 120, y: 50), size: image.size)
let quantityText = "Quantity"
quantityText.draw(in: quantityRect, withAttributes: toFromFontAttributes)
......
// add other items
......
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage ?? nil
}

CGContext renders text upside down

I am rendering a NSAttributedString with CGContext, however when it renders the text is upside down :(
This is what I came up with:
override func draw(with box: PDFDisplayBox, in context: CGContext) {
UIGraphicsPushContext(context)
context.saveGState()
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let attributes = [
NSAttributedString.Key.paragraphStyle: paragraphStyle,
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 80.0),
NSAttributedString.Key.foregroundColor: UIColor.red
]
NSAttributedString(string: self.widgetStringValue!, attributes: attributes).draw(in: self.bounds)
context.restoreGState()
UIGraphicsPopContext()
}
I have tried adding this:
context.translateBy(x: 0.0, y: bounds.height)
context.scaleBy(x: 1.0, y: -1.0)
But then the text does not appear on my screen at all :(
What am I doing wrong?
UPDATE
As requested here is my full TextAnnotation class:
class TextAnnotation: PDFAnnotation {
var currentText: String?
override init(bounds: CGRect, forType annotationType: PDFAnnotationSubtype, withProperties properties: [AnyHashable : Any]?) {
super.init(bounds: bounds, forType: annotationType, withProperties: properties)
self.widgetFieldType = PDFAnnotationWidgetSubtype(rawValue: PDFAnnotationWidgetSubtype.text.rawValue)
self.font = UIFont.systemFont(ofSize: 80)
self.isMultiline = true
self.widgetStringValue = "Text Here"
self.currentText = self.widgetStringValue!
}
override func draw(with box: PDFDisplayBox, in context: CGContext) {
UIGraphicsPushContext(context)
context.saveGState()
let pageBounds = bounds
context.translateBy(x: 0, y: pageBounds.height)
context.scaleBy(x: 1, y: -1)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let attributes: [NSAttributedString.Key: Any] = [
.paragraphStyle: paragraphStyle,
.font: UIFont.systemFont(ofSize: 80),
.foregroundColor: UIColor.red
]
widgetStringValue!.draw(in: pageBounds, withAttributes: attributes)
context.restoreGState()
UIGraphicsPopContext()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
In my case, I was subclassing a PDFAnnotation. The key was using the correct y-value (which was a pain to figure out) for the translateBy call in my draw method:
override func draw(with box: PDFDisplayBox, in context: CGContext) {
let text = NSString(string: "Hello!")
UIGraphicsPushContext(context)
context.saveGState()
context.translateBy(x: 0, y: bounds.height + (2 * bounds.minY))
context.scaleBy(x: 1, y: -1.0)
text.draw(in: bounds.offsetBy(dx: 2, dy: 0), withAttributes: attributes)
context.restoreGState()
UIGraphicsPopContext()
}
In a PDFAnnotation, you should just add the translateBy(x:y:) and scaledBy(x:y:) as you’ve discussed:
override func draw(with box: PDFDisplayBox, in context: CGContext) {
UIGraphicsPushContext(context)
context.saveGState()
context.translateBy(x: 0, y: bounds.height)
context.scaleBy(x: 1, y: -1)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let attributes: [NSAttributedString.Key: Any] = [
.paragraphStyle: paragraphStyle,
.font: UIFont.systemFont(ofSize: 80),
.foregroundColor: UIColor.red
]
widgetStringValue?.draw(in: bounds, withAttributes: attributes)
context.restoreGState()
UIGraphicsPopContext()
}
In a PDFPage you should use bounds(for:) to get the bounds within that PDFDisplayBox, and then use translateBy(x:y:) and scaledBy(x:y:) as you’ve discussed:
override func draw(with box: PDFDisplayBox, to context: CGContext) {
UIGraphicsPushContext(context)
context.saveGState()
let pageBounds = bounds(for: box)
context.translateBy(x: 0, y: pageBounds.height)
context.scaleBy(x: 1, y: -1)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let attributes: [NSAttributedString.Key: Any] = [
.paragraphStyle: paragraphStyle,
.font: UIFont.systemFont(ofSize: 80),
.foregroundColor: UIColor.red
]
text.draw(in: pageBounds, withAttributes: attributes)
context.restoreGState()
UIGraphicsPopContext()
}

UIProgressBar: How to Change UILabel Color according to Background Color

I'm new to iOS programming. I want to create a progress bar with a UIlabel which also change text color according to background color like this:
Please don't mark the question as duplicate. Because the solution I found are in Obj C or some Pods. But I wanted the solution in Swift because I didn't have any knowledge about Obj-C.
Thanks!
If you want an answer in swift, here is the code(changed from objc to swift) from this post, which should be exactly what you need:
This is swift 4
class MyProgressView: UIView {
var progress: CGFloat = 0 {
didSet {
setNeedsDisplay()
}
}
override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
// Set up environment.
let size = bounds.size
let backgroundColor = UIColor(red: 108/255, green: 200/255, blue: 226/255, alpha: 1)
let foregroundColor = UIColor.white
let font = UIFont.boldSystemFont(ofSize: 42)
// Prepare progress as a string.
let progress = NSString(format: "%d%%", Int(round(self.progress * 100))) // this cannot be a String because there are many subsequent calls to NSString-only methods such as `size` and `draw`
var attributes: [NSAttributedString.Key: Any] = [.font: font]
let textSize = progress.size(withAttributes: attributes)
let progressX = ceil(self.progress * size.width)
let textPoint = CGPoint(x: ceil((size.width - textSize.width) / 2), y: ceil((size.height - textSize.height) / 2))
// Draw background + foreground text
backgroundColor.setFill()
context?.fill(bounds)
attributes[.foregroundColor] = foregroundColor
progress.draw(at: textPoint, withAttributes: attributes)
// Clip the drawing that follows to the remaining progress's frame
context?.saveGState()
let remainingProgressRect = CGRect(x: progressX, y: 0, width: size.width - progressX, height: size.height)
context?.addRect(remainingProgressRect)
context?.clip()
// Draw again with inverted colors
foregroundColor.setFill()
context?.fill(bounds)
attributes[.foregroundColor] = backgroundColor
progress.draw(at: textPoint, withAttributes: attributes)
context?.restoreGState()
}
}
Tested with playground

CATextLayer not visible

I have implemented a function to draw the text use of CATextLayer. But after drawing the text is not visible.
Here is my code:
func addText() -> CATextLayer{
let rect:CGRect = CGRect(x: 50, y: 600, width: 120, height: 60)
let myAttributes = [
NSFontAttributeName: UIFont(name: "HelveticaNeue-Thin", size:18)!,
NSForegroundColorAttributeName: UIColor.black.cgColor
] as [String : Any]
let myAttributedString = NSAttributedString(string: "TEST STRING", attributes: myAttributes)
let textLayer = CATextLayer()
textLayer.bounds = rect
textLayer.string = myAttributedString
textLayer.position = CGPoint(x:150,y:400)
textLayer.alignmentMode = kCAAlignmentCenter
textLayer.displayIfNeeded()
return textLayer
}
Does anyone know the problem?

Resources