how to add image inside text and resize it as per the text font

Generated on 9/6/2024

2 searches

To add an image inside text and resize it according to the text font, you can use the scaled metric API in SwiftUI or UIKit. Here's how you can achieve this:

SwiftUI

In SwiftUI, you can interpolate the image directly in the text. If you have an image or a PDF in your assets, you can use the scaled metric API to let the image resize based on the selected text size. Simply add a scaled metric and specify the width or the height of the image. This value will automatically scale at runtime when the text size changes.

UIKit

In UIKit, you can achieve this behavior by using UIImage symbol configuration. You can create a configuration with a specific text style using symbol configuration with text style. Then, create your UIImage with that symbol configuration. Additionally, you can use NSAttributedString to create an attributed string with an image as an NSTextAttachment and append that to an attributed string.

For more detailed guidance, you can refer to the session Get started with Dynamic Type (10:04) which covers how to handle images and text scaling in SwiftUI and UIKit.