Convert Apple Emoji (String) to UIImage

前端 未结 8 976
野的像风
野的像风 2020-12-12 21:53

I need all Apple Emojis.
I can get all the emojis and put them into a String by copying them from the site getemoji but in my app i need the emojis in the right

8条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-12 22:35

    Updated for Swift 4.1

    Add this extension to your project

    import UIKit
    
    extension String {
        func image() -> UIImage? {
            let size = CGSize(width: 40, height: 40)
            UIGraphicsBeginImageContextWithOptions(size, false, 0)
            UIColor.white.set()
            let rect = CGRect(origin: .zero, size: size)
            UIRectFill(CGRect(origin: .zero, size: size))
            (self as AnyObject).draw(in: rect, withAttributes: [.font: UIFont.systemFont(ofSize: 40)])
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return image
        }
    }
    

    The code above draws the current String to an Image Context with a white background color and finally transform it into a UIImage.

    Now you can write

    Example

    Given a list of ranges indicating the unicode values of the emoji symbols

    let ranges = [0x1F601...0x1F64F, 0x2702...0x27B0]
    

    you can transform it into a list of images

    let images = ranges
        .flatMap { $0 }
        .compactMap { Unicode.Scalar($0) }
        .map(Character.init)
        .compactMap { String($0).image() }
    

    Result:

    I cannot guarantee the list of ranges is complete, you'll need to search for it by yourself

提交回复
热议问题