将绘图内容绘制到UIImage中

5

如何在monotouch中对现有的UIImage进行绘制?

我加载一张图片:UIImage.FromFile("MyImage.png")

然后我想在这个图片上绘制一个字符串和一些线条。

有人有代码示例吗?

谢谢

1个回答

10

这里有一个可以实现它的方法:

private void drawOnTouch(object data)
{

    UITouch touch = data as UITouch;

    if (null != touch)
    {

        UIGraphics.BeginImageContext(this.Image == null ? this.Frame.Size : this.Image.Size);

        using (CGContext cont = UIGraphics.GetCurrentContext())
        {

            if (this.Image != null)
            {

                cont.TranslateCTM(0f, this.Image.Size.Height);
                cont.ScaleCTM(1.0f, -1.0f);
                cont.DrawImage(new RectangleF(0f,0f,this.Image.Size.Width, this.Image.Size.Height), this.Image.CGImage);
                cont.ScaleCTM(1.0f, -1.0f);
                cont.TranslateCTM(0f, -this.Image.Size.Height);


            } //end if

            PointF lastLocation = touch.PreviousLocationInView(this);
            PointF pt = touch.LocationInView(this);
            using (CGPath path = new CGPath())
            {

                cont.SetLineCap(CGLineCap.Round);
                cont.SetLineWidth(3);
                cont.SetRGBStrokeColor(0, 2, 3, 1);
                path.MoveToPoint(lastLocation.X, lastLocation.Y);
                path.AddLines(new PointF[] { new PointF(lastLocation.X, 
                                lastLocation.Y),
                            new PointF(pt.X, pt.Y) });
                path.CloseSubpath();

                cont.AddPath(path);
                cont.DrawPath(CGPathDrawingMode.FillStroke);
                this.Image = UIGraphics.GetImageFromCurrentImageContext();

            }//end using path


        }//end using cont
        UIGraphics.EndImageContext();
        this.SetNeedsDisplay();

    }//end if


}//end void drawOnTouch

如果你将这个方法放在UIImageView的子类中,并且在TouchesBegan和TouchesMoved中调用它,当你触摸屏幕时它将在图像上绘制。


很不幸,目前的Xamarin和iOS版本对我来说并不正常工作。你能否重新审查一下你的代码? - WhiteIntel
很抱歉,我7年前的答案对你没有用。不,我不能审核我的代码。 - Dimitris Tavlikos

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接