1
基本上,我想爲圖像添加一個任意文本的區域。所以之後圖像尺寸變大。這是我想出來的:將多行文本區域添加到圖像
public partial class ViewController : UIViewController
{
public override void ViewDidLoad()
{
base.ViewDidLoad();
string filename = "TestImage.jpg";
string bundlePath = NSBundle.MainBundle.BundlePath;
string sourcePath = Path.Combine(bundlePath, filename);
string docPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string destinationPath = Path.Combine(docPath, filename);
File.Copy(sourcePath, destinationPath, true);
string testString = "Lorem ipsum dolor sit amet";
this.AddTextToImage(testString, destinationPath);
var imageView = new UIImageView(new CGRect(0, 0, 500, 500));
imageView.ContentMode = UIViewContentMode.ScaleAspectFit;
imageView.Image = UIImage.FromFile(destinationPath);
this.View.AddSubview(imageView);
this.View.BackgroundColor = UIColor.Red;
}
public void AddTextToImage(string texttoadd, string filepath)
{
UIImage image = UIImage.FromFile(filepath);
nfloat fontSize = 16;
nfloat fWidth = image.Size.Width;
nfloat fHeight = image.Size.Height;
nfloat textWidth;
nfloat textHeight;
CGColorSpace colorSpace = CGColorSpace.CreateDeviceRGB();
UIFont font = UIFont.FromName("Helvetica", fontSize);
NSParagraphStyle style = new NSMutableParagraphStyle();
style.LineBreakMode = UILineBreakMode.WordWrap;
NSAttributedString attributedString = new NSAttributedString(texttoadd, font: font, foregroundColor: UIColor.Blue, paragraphStyle: style);
CGRect stringSize = attributedString.GetBoundingRect(new CGSize(fWidth, double.MaxValue), NSStringDrawingOptions.UsesLineFragmentOrigin | NSStringDrawingOptions.UsesFontLeading, null);
textWidth = (nfloat)Math.Ceiling(stringSize.Width);
textHeight = (nfloat)Math.Ceiling(stringSize.Height);
nfloat fullWidth = fWidth;
nfloat fullHeight = fHeight + textHeight;
UIImage composition;
using (CGBitmapContext ctx = new CGBitmapContext(IntPtr.Zero, (nint)fullWidth, (nint)fullHeight, 8, 4 * (nint)fullWidth, CGColorSpace.CreateDeviceRGB(), CGImageAlphaInfo.PremultipliedFirst))
{
CGRect frameRect = new CGRect(0, 0, fullWidth, fullHeight);
ctx.SetFillColor(UIColor.Yellow.CGColor);
ctx.FillRect(frameRect);
CGRect imageRect = new CGRect(0, textHeight, (double)fWidth, (double)fHeight);
ctx.DrawImage(imageRect, image.CGImage);
CGPath stringPath = new CGPath();
stringPath.AddRect(new CGRect(0, 0, textWidth, textHeight));
CTFramesetter framesetter = new CTFramesetter(attributedString);
CTFrame frame = framesetter.GetFrame(new NSRange(0, attributedString.Length), stringPath, null);
frame.Draw(ctx);
using (var imageRef = ctx.ToImage())
composition = new UIImage(imageRef);
}
NSData data = composition.AsJPEG();
NSError error;
data.Save(filepath, NSDataWritingOptions.FileProtectionNone, out error);
}
}
目前,我有以下問題:
- 文本被裁剪(例如
fontSize = 160;
)。多行文字似乎不起作用。 - 文本根本不顯示(例如
fontSize = 16;
)。
你可以在Objective-C,Swift或C#中提供答案 - 我會試着翻譯它。