Getting wrong text height? - ios

I am using below code to determine the hight of text , it works fine for small text but if text is large it gives me wrong height(too much space at bottom of textview) how to fix that.
let textView = UITextView (frame: CGRectMake(0,0,maxWidth, 10))
textView.font = font
textView.text = text
//textView.textContainerInset = UIEdgeInsetsZero
let fixedWidth = textView.frame.size.width
let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max))
var newFrame = textView.frame
newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
textView.frame = newFrame;
return textView.frame.height

This will be your text height in textview.
let textView = UITextView (frame: CGRectMake(0,0,maxWidth, 10))
textView.font = font
textView.text = text
let height = textView.conentSize.height

Use an extension on String
extension String {
func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
let boundingBox = boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
return boundingBox.height
}
}
and also on NSAttributedString (which is very useful at times)
extension NSAttributedString {
func height(withConstrainedWidth width: CGFloat) -> CGFloat {
let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
let boundingBox = boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, context: nil)
return boundingBox.height
}
func width(withConstrainedHeight height: CGFloat) -> CGFloat {
let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
let boundingBox = boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, context: nil)
return boundingBox.width
}
}

Try with this method
static func neededHeigthForText(text:String,font:UIFont,maxWidth:CGFloat) ->CGFloat
{
let options : NSStringDrawingOptions = [.usesLineFragmentOrigin,.usesFontLeading]
let style : NSMutableParagraphStyle = NSMutableParagraphStyle()
style.lineBreakMode = .byWordWrapping
let textAttributes = [NSFontAttributeName:font]
let size = NSString(string: text).boundingRect(with: CGSize(width: maxWidth, height: CGFloat.greatestFiniteMagnitude) , options: options, attributes: textAttributes, context: nil).size
return size.height
}
I hope this helps you

Related

Why row height is squeezing after scroll for tableView in swift?

I am using a tableView and with the tableView I am using a label and my requirement is to make the label auto-adjusting according to the text. So I am calculating dynamic height for my label. It is working fine initially but after scroll the height of the label is reduced. I don't know why.
// to calculate dynamic height of the label
func height(constraintedWidth width: CGFloat, font: UIFont) -> CGFloat {
let label = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: .greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.text = self
label.font = font
label.sizeToFit()
return label.frame.height
}
you can try!
extension UILabel {
func textWidth() -> CGFloat {
return UILabel.textWidth(label: self)
}
func textHeight() -> CGFloat {
return UILabel.textHeight(withWidth: self.frame.width, font: self.font, text: self.text ?? "")
}
class func textWidth(label: UILabel) -> CGFloat {
return textWidth(label: label, text: label.text!)
}
class func textWidth(label: UILabel, text: String) -> CGFloat {
return textWidth(font: label.font, text: text)
}
class func textWidth(font: UIFont, text: String) -> CGFloat {
return textSize(font: font, text: text).width
}
class func textHeight(withWidth width: CGFloat, font: UIFont, text: String) -> CGFloat {
return textSize(font: font, text: text, width: width).height
}
class func textSize(font: UIFont, text: String, extra: CGSize) -> CGSize {
var size = textSize(font: font, text: text)
size.width = size.width + extra.width
size.height = size.height + extra.height
return size
}
class func textSize(font: UIFont, text: String, width: CGFloat = .greatestFiniteMagnitude, height: CGFloat = .greatestFiniteMagnitude) -> CGSize {
let label = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: height))
label.numberOfLines = 0
label.font = font
label.text = text
label.sizeToFit()
return label.frame.size
}
class func countLines(font: UIFont, text: String, width: CGFloat, height: CGFloat = .greatestFiniteMagnitude) -> Int {
// Call self.layoutIfNeeded() if your view uses auto layout
let myText = text as NSString
let rect = CGSize(width: width, height: height)
let labelSize = myText.boundingRect(with: rect, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
return Int(ceil(CGFloat(labelSize.height) / font.lineHeight))
}
func countLines(width: CGFloat = .greatestFiniteMagnitude, height: CGFloat = .greatestFiniteMagnitude) -> Int {
// Call self.layoutIfNeeded() if your view uses auto layout
let myText = (self.text ?? "") as NSString
let rect = CGSize(width: width, height: height)
let labelSize = myText.boundingRect(with: rect, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: self.font], context: nil)
return Int(ceil(CGFloat(labelSize.height) / self.font.lineHeight))
}
}

UIImage With Color & Centered Text

I'm trying to add a convenience initialiser to the UIImage which will allow me to create an image with a given text centred in the middle, and given background color:
I've got the following code:
public convenience init?(color: UIColor, withText: String, withTextColor: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
color.setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let label = UILabel()
label.text = withText
label.textAlignment = .center
label.font = UIFont.boldSystemFont(ofSize: 40)
label.textColor = withTextColor
guard let cgImage = image?.cgImage else { return nil }
self.init(cgImage: cgImage)
}
This creates the image with the correct background color - I'm not sure how to embed the UILabel in the middle of the image though.
EDIT
Attributed strings know how to draw themselves, so you don't need a label. They also can tell you how big they are or even wrap to fit an available width. Here is playground that shows how to get an image from any attributed string:
import UIKit
import PlaygroundSupport
extension NSAttributedString {
func asImage(size: CGSize = .init(width: .max, height: .max)) -> UIImage {
UIGraphicsImageRenderer(bounds: boundingRect(with: size, options: [.usesLineFragmentOrigin], context: nil)).image { context in
self.draw(at: .zero)
}
}
}
let attributedString = NSAttributedString.init(string: "testing", attributes: [NSAttributedString.Key.foregroundColor : UIColor.white])
let image = attributedString.asImage()
let imageView = UIImageView(image: image)
PlaygroundPage.current.liveView = imageView
Here is the convenience initialiser drawing white text in the centre of a red image:
convenience init?(letters: String) {
let style = NSMutableParagraphStyle()
style.alignment = NSTextAlignment.center
let sizeOfImage = CGSize(width: 120, height: 120)
let font = UIFont(name: "Georgia", size: 50)!
let imageText = NSAttributedString(string: letters, attributes: [.font: font, .foregroundColor: UIColor.white, .paragraphStyle: style])
let textHight = font.lineHeight
let renderer = UIGraphicsImageRenderer(size: sizeOfImage)
let image = renderer.image { context in
UIColor.red.setFill()
context.fill(CGRect(origin: .zero, size: sizeOfImage))
imageText.draw(in: CGRect(origin: CGPoint(x: 0, y: (sizeOfImage.height - textHight) / 2), size: sizeOfImage))
}
self.init(cgImage: image.cgImage!)
}

How UILabel height according to text height in Swift programmatically

I tried a many solutions but not get a right answer.
Here my code:
self.AhadeesView = UILabel()
self.AhadeesView.translatesAutoresizingMaskIntoConstraints = false
self.AhadeesView.backgroundColor = UIColor.orange
self.AhadeesView.numberOfLines = 0
self.AhadeesView.text = NSLocalizedString("TitleAhadees", comment: "Title Ahadees of the App")
self.AhadeesView.textAlignment = .center
self.AhadeesView.font = UIFont(name:"Jameel-Noori-Nastaleeq",size:25)
self.AhadeesView.lineBreakMode = NSLineBreakMode.byWordWrapping
// self.AhadeesView.sizeToFit()
containerView1.addSubview(AhadeesView)
Seems like you have missed your frame to show the label.
self.AhadeesView = UILabel(frame: [your frame value])
Frame can be created by
let frame = CGRect(x: 0, y: 0, width: 320, height: [height_of_String])
[height_of_String] can be calculated by below extension
You can calculate the width and height of the string using the following extension methods
extension String {
//To calculate the height u need to pass the width of the label and the required font size.
func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
return ceil(boundingBox.height)
}
func width(withConstraintedHeight height: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
return ceil(boundingBox.width)
}
}

Add UILabel on UIImage to create a new UIImage [duplicate]

I have looked around and have been unsuccessful at figuring out how take text, overlay it on an image, and then combine the two into a single UIImage.
I have exhausted Google using the search terms I can think of so if anyone has a solution or at least a hint they can point to it would be greatly appreciated.
I figured it out:
func textToImage(drawText: NSString, inImage: UIImage, atPoint: CGPoint) -> UIImage{
// Setup the font specific variables
var textColor = UIColor.whiteColor()
var textFont = UIFont(name: "Helvetica Bold", size: 12)!
// Setup the image context using the passed image
let scale = UIScreen.mainScreen().scale
UIGraphicsBeginImageContextWithOptions(inImage.size, false, scale)
// Setup the font attributes that will be later used to dictate how the text should be drawn
let textFontAttributes = [
NSFontAttributeName: textFont,
NSForegroundColorAttributeName: textColor,
]
// Put the image into a rectangle as large as the original image
inImage.drawInRect(CGRectMake(0, 0, inImage.size.width, inImage.size.height))
// Create a point within the space that is as bit as the image
var rect = CGRectMake(atPoint.x, atPoint.y, inImage.size.width, inImage.size.height)
// Draw the text into an image
drawText.drawInRect(rect, withAttributes: textFontAttributes)
// Create a new image out of the images we have created
var newImage = UIGraphicsGetImageFromCurrentImageContext()
// End the context now that we have the image we need
UIGraphicsEndImageContext()
//Pass the image back up to the caller
return newImage
}
To call it, you just pass in an image:
textToImage("000", inImage: UIImage(named:"thisImage.png")!, atPoint: CGPointMake(20, 20))
The following links helped me get this straight:
Swift - Drawing text with drawInRect:withAttributes:
How to write text on image in Objective-C (iOS)?
The original goal was to create a dynamic image that I could use in an AnnotaionView such as putting a price at a given location on a map and this worked out great for it.
For Swift 3:
func textToImage(drawText text: NSString, 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 = [
NSFontAttributeName: textFont,
NSForegroundColorAttributeName: textColor,
] as [String : 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!
}
For Swift 4:
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 = [
NSAttributedStringKey.font: textFont,
NSAttributedStringKey.foregroundColor: textColor,
] as [NSAttributedStringKey : 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!
}
For Swift 5:
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!
}
My simple solution:
func generateImageWithText(text: String) -> UIImage? {
let image = UIImage(named: "imageWithoutText")!
let imageView = UIImageView(image: image)
imageView.backgroundColor = UIColor.clear
imageView.frame = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
let label = UILabel(frame: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height))
label.backgroundColor = UIColor.clear
label.textAlignment = .center
label.textColor = UIColor.white
label.text = text
UIGraphicsBeginImageContextWithOptions(label.bounds.size, false, 0)
imageView.layer.render(in: UIGraphicsGetCurrentContext()!)
label.layer.render(in: UIGraphicsGetCurrentContext()!)
let imageWithText = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return imageWithText
}
You can also do a CATextLayer.
// 1
let textLayer = CATextLayer()
textLayer.frame = someView.bounds
// 2
let string = String(
repeating: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce auctor arcu quis velit congue dictum. ",
count: 20
)
textLayer.string = string
// 3
let fontName: CFStringRef = "Noteworthy-Light"
textLayer.font = CTFontCreateWithName(fontName, fontSize, nil)
// 4
textLayer.foregroundColor = UIColor.darkGray.cgColor
textLayer.isWrapped = true
textLayer.alignmentMode = kCAAlignmentLeft
textLayer.contentsScale = UIScreen.main.scale
someView.layer.addSublayer(textLayer)
https://www.raywenderlich.com/402-calayer-tutorial-for-ios-getting-started
I have created an extension for using it everywhere :
import Foundation
import UIKit
extension UIImage {
class func createImageWithLabelOverlay(label: UILabel,imageSize: CGSize, image: UIImage) -> UIImage {
UIGraphicsBeginImageContextWithOptions(CGSize(width: imageSize.width, height: imageSize.height), false, 2.0)
let currentView = UIView.init(frame: CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height))
let currentImage = UIImageView.init(image: image)
currentImage.frame = CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height)
currentView.addSubview(currentImage)
currentView.addSubview(label)
currentView.layer.render(in: UIGraphicsGetCurrentContext()!)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img!
}
}
Usage :
Anywhere on your ViewController where you have the size and the label to add use it as follows -
let newImageWithOverlay = UIImage.createImageWithLabelOverlay(label: labelToAdd, imageSize: size, image: editedImage)
For swift 4:
func textToImage(drawText text: NSString, inImage image: UIImage, atPoint point: CGPoint) -> UIImage {
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(image.size, false, scale)
image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))
let rect = CGRect(origin: point, size: image.size)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let attrs = [NSAttributedStringKey.font: UIFont(name: "Helvetica Bold", size: 12)!,NSAttributedStringKey.foregroundColor : UIColor.white , NSAttributedStringKey.paragraphStyle: paragraphStyle]
text.draw(with: rect, options: .usesLineFragmentOrigin, attributes: attrs, context: nil)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
I can't see anything in your initial question suggesting that this must be done exclusively in code - so why not simply add a UILabel in interface builder, and add constraints to give it the same length and width as your image, center it vertically and horizontally (or however you need it placed), delete the label text, set the text font, size, colour, etc. as needed (including ticking Autoshrink with whatever minimum size or scale you need), and ensure it's background is transparent.
Then just connect it to an IBOutlet, and set the text in code as needed (e.g. in viewWillAppear, or by using a ViewModel approach and setting it on initialisation of your view/viewcontroller).
I have tried this basic components. Hope it will work.
func imageWithText(image : UIImage, text : String) -> UIImage {
let outerView = UIView(frame: CGRect(x: 0, y: 0, width: image.size.width / 2, height: image.size.height / 2))
let imgView = UIImageView(frame: CGRect(x: 0, y: 0, width: outerView.frame.width, height: outerView.frame.height))
imgView.image = image
outerView.addSubview(imgView)
let lbl = UILabel(frame: CGRect(x: 5, y: 5, width: outerView.frame.width, height: 200))
lbl.font = UIFont(name: "HelveticaNeue-Bold", size: 70)
lbl.text = text
lbl.textAlignment = .left
lbl.textColor = UIColor.blue
outerView.addSubview(lbl)
let renderer = UIGraphicsImageRenderer(size: outerView.bounds.size)
let convertedImage = renderer.image { ctx in
outerView.drawHierarchy(in: outerView.bounds, afterScreenUpdates: true)
}
return convertedImage
}
It's also possible to use the QLPreviewController. Just save the imageFile to an url like the applicationsDocuments directory under the .userDomainMask and open the apple' editor. You can draw, add shapes, arrow and even your signature.
I explained the implementation in detail in the following post:
https://stackoverflow.com/a/68743098/12035498

Making NSMutableAttributedString and sizeThatFits work together

I'm having issues making NSMutableAttributedString and sizeThatFits work together. I have a UILabel that must be no wider than a constant self.frame.size.width-usernameX-horizontalMargin. I want the UILabel to be one line if it fits or two lines with a hyphen if it is too long. Currently I am using this code:
let usernameX = profilePhoto.frame.size.width+horizontalMargin
let username = UILabel()
username.adjustsFontSizeToFitWidth = false
username.font = UIFont(name: "SFUIDisplay-Regular", size: 18)
username.numberOfLines = 0
username.translatesAutoresizingMaskIntoConstraints = false
//Set hyphenation
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.hyphenationFactor = 0.2
username.attributedText = NSMutableAttributedString(string: displayName, attributes: [NSParagraphStyleAttributeName: paragraphStyle])
let maxSize = CGSize(width: self.frame.size.width-usernameX-horizontalMargin, height: CGFloat.max)
let requiredSize = username.sizeThatFits(maxSize)
username.frame = CGRect(x: usernameX, y: (self.frame.size.height/2)-21, width: requiredSize.width, height: requiredSize.height)
self.addSubview(username)
Currently the text displays as just one line with a hyphen. The second line isn't showing. Any ideas what I might be doing wrong here? I have tried setting the number of lines to 2, that made no difference. Any pointers would be really appreciated.
Thanks!
You need to include your font also in attributes, else it will take default fond for attributed text. Can you try this out?
let attributedString = NSMutableAttributedString(string: displayName, attributes: [NSParagraphStyleAttributeName: paragraphStyle, NSFontAttributeName : UIFont(name: "SFUIDisplay-Regular", size: 18)])
var newFrame = attributedString.boundingRectWithSize(CGSizeMake(self.frame.size.width-usernameX-horizontalMargin, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin , context: nil)
username.frame = CGRect(x: usernameX, y: (self.frame.size.height/2)-21, width: newFrame.size.width, height: newFrame.size.height)
If you want to use sizeThatFits you can use following
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.hyphenationFactor = 0.2
username.attributedText = NSMutableAttributedString(string: displayName, attributes: [NSParagraphStyleAttributeName: paragraphStyle, NSFontAttributeName : UIFont(name: "SFUIDisplay-Regular", size: 18)])
let maxSize = CGSize(width: self.frame.size.width-usernameX-horizontalMargin, height: CGFloat.max)
let requiredSize = username.sizeThatFits(maxSize)
username.frame = CGRect(x: usernameX, y: (self.frame.size.height/2)-21, width: requiredSize.width, height: requiredSize.height)
self.addSubview(username)

Resources