Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw into UIImage

how can I draw into an existing UIImage using monotouch?

I load an image: UIImage.FromFile("MyImage.png")

Then I want to draw a string and some lines into this image.

Does anyone has a code sample?

Thx

like image 895
Marco Avatar asked Mar 28 '11 16:03

Marco


1 Answers

Here is a method that does it:

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

If you place this method in a subclass of UIImageView and call it from TouchesBegan and TouchesMoved, when you touch the screen it will draw on the image.

like image 51
Dimitris Tavlikos Avatar answered Oct 22 '22 01:10

Dimitris Tavlikos