基本上,我想在图像中添加带有任意文本的区域。因此,之后图像尺寸变得更大。这就是我提出的:
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#中提供答案 - 我会尝试翻译它。
答案 0 :(得分:1)
似乎字体是问题。使用
UIFont font = UIFont.SystemFontOfSize(fontSize);
现在可以在不切断文字的情况下完成工作。剩下的唯一问题是,为什么?