在UIImage NOT UIImageView上绘制线条 - Xamarin iOS

时间:2017-08-08 20:39:58

标签: ios xamarin.ios uiimageview uiimage

您好我目前有这种方法在UIImageView上绘制线条。

但是我试图让它与UIImage兼容并且没有任何运气。 This example here可以很好地处理文本,但不适合行。

DrawOnUIImageView.cs

 private void Draw(Face face, UIImageView imageView)
{
    CAShapeLayer boundingBoxLayer = new CAShapeLayer();
    boundingBoxLayer.Frame = face.rect;
    boundingBoxLayer.FillColor = null;
    boundingBoxLayer.StrokeColor = UIColor.Red.CGColor;
    imageView.Layer.AddSublayer(boundingBoxLayer);

    CAShapeLayer secondBoxLayer = new CAShapeLayer();
    secondBoxLayer.FillColor = null;
    secondBoxLayer.StrokeColor = UIColor.Green.CGColor;
    boundingBoxLayer.AddSublayer(secondBoxLayer);

    var path = new CGPath();
    List<LandmarkLine> lines = new List<LandmarkLine>();
    foreach (var landmark in face.landmarks)
    {
        List<CGPoint> addTo = new List<CGPoint>();
        foreach (var point in landmark.points)
        {
            addTo.Add(new CGPoint((point.X * face.rect.Width), (1 - point.Y) * face.rect.Height));
        }
        CGPath outline = new CGPath();
        outline.AddLines(addTo.ToArray());
        outline.CloseSubpath();
        path.AddPath(outline);
    }
    secondBoxLayer.Path = path;
    //imageView.Layer.AddSublayer(outline);
}

对此的任何建议都会很棒。感谢

1 个答案:

答案 0 :(得分:2)

您可以像这样在图像上画一条线:

        private UIImage drawLineOnImage(UIImage img)
        {

            //UIImage orgImage = <YOUR IMAGE> 

            UIGraphics.BeginImageContext(orgImage.Size);

            // 1: Draw the original image as the background
            orgImage.Draw(new RectangleF(0,0,(float)orgImage.Size.Width,(float)orgImage.Size.Height));

            // 2: Draw the line on the image
            CGContext context = UIGraphics.GetCurrentContext();
            context.SetLineWidth(1.0f);
            context.MoveTo(0, 80);
            context.AddLineToPoint(orgImage.Size.Width, 80);
            context.SetStrokeColor(UIColor.Blue.CGColor);
            context.StrokePath();

            // Create new image
            UIImage image = UIGraphics.GetImageFromCurrentImageContext();

            // Tidy up
            UIGraphics.EndImageContext();

            return image;
        }

此代码将创建一个新图像作为原始图像大小,然后将原始图像的副本绘制到新图像上并在新图像上绘制一条线。