IOSUITextView图⽂混排显⽰⽂本和表情
ViewController类
using System;
using UIKit;
using Foundation;
namespace EmojiDemo
{
public partial class ViewController : UIViewController
{
public ViewController (IntPtr handle) : ba (handle)
{
}
public override void ViewDidLoad ()
{
ba.ViewDidLoad ();
NSString normalStr = new NSString("This category[kiss] allows you to [hug]convert string into given image like this [kiss] and this55");
UIFont font = UIFont.SystemFontOfSize (15);
txtEmoji.TextColor = UIColor.Red;
txtEmoji.AttributedText = new NSAttributedStringAndJATEmoji ().emojiAttributedString (normalStr, font);
}
public override void DidReceiveMemoryWarning ()
{
ba.DidReceiveMemoryWarning ();
}
}
}
NSAttributedStringAndJATEmoji类
using System;
using UIKit;
using Foundation;
using System.Drawing;
using CoreGraphics;
namespace EmojiDemo
{
public partial class NSAttributedStringAndJATEmoji
{
public NSAttributedString emojiAttributedString(NSString str,UIFont font)
{
NSError error = new NSError ();
UIStringAttributes s = new UIStringAttributes ();
s.Font = font;
s.ForegroundColor = UIColor.Red;
NSMutableAttributedString pardOutPut = new NSMutableAttributedString (str,s);
NSString strs = new NSString (pardOutPut.ToString ());
string plistPath = NSBundle.MainBundle.PathForResource ("Emoji", "plist");
NSDictionary emojiPlistDic = new NSDictionary(plistPath);
CGSize emojiSize = new CGSize (font.LineHeight, font.LineHeight);
var list =System.Text.RegularExpressions.Regex.Matches(strs, @"\[[A-Za-z0-9]*\]");
for (int i = list.Count; i > 0; i--) {
NSRange matchRange = new NSRange (list[i-1].Index, list[i-1].Length);
string placeholder = pardOutPut.ToString ().Substring(list[i-1].Index,list[i-1].Length);
string imgpath=NSBundle.MainBundle.PathForResource ("Images/"+emojiPlistDic[placeholder].ToString(), "png"); UIImage emojiImage = UIImage.FromBundle (imgpath);
UIGraphics.BeginImageContextWithOptions (emojiSize, fal,(nfloat)0);
emojiImage.Draw (new CGRect (0, 0, emojiSize.Width, emojiSize.Height));
UIImage resizedImage = UIGraphics.GetImageFromCurrentImageContext ();
UIGraphics.EndImageContext ();
NSTextAttachment textAtachment = new NSTextAttachment ();
textAtachment.Image = resizedImage;
textAtachment.Bounds = new CGRect (0, -4, emojiSize.Width, emojiSize.Height);
NSAttributedString rep = NSAttributedString.CreateFrom (textAtachment);
pardOutPut.Replace (matchRange, rep);
}
return new NSAttributedString (pardOutPut);
}
}
}