Question

Here is my function:

private byte[] GetByteArray(IPhotoObject photo)
{
        _addCanvas.RenderTransformOrigin = new Point(0.5, 0.5);
        _addCanvas.RenderTransform = new RotateTransform(90.0);

        BinaryImageConverter converter = new BinaryImageConverter();
        Image i = new Image();
        BitmapSource source = (BitmapImage)converter.Convert(photo.ImageBytes, typeof (BitmapSource), null, null);
        i.Stretch = Stretch.None;
        i.Width = source.PixelWidth;
        i.Height = source.PixelHeight;
        i.SetValue(Image.SourceProperty,source);
        var width = source.PixelWidth;
        var height = source.PixelHeight;

        Canvas canvas = new Canvas();
        canvas.Width = width;
        canvas.Height = height;
        canvas.Children.Add(i);
        canvas.Children.Add(_addCanvas);
        var size = new Size(width, height);
        var rect = new Rect(size);
        canvas.Measure(size);
        canvas.Arrange(rect);

        RenderTargetBitmap bmp = new RenderTargetBitmap(
            Convert.ToInt32(width),
            Convert.ToInt32(height),
            96.0,
            96.0,
            PixelFormats.Default);
        bmp.Render(canvas);

        return XImage.GetJpegByteArrayFromWritableBitmap(new WriteableBitmap(bmp));
}

My problem is _addCanvas. It's not getting drawn to the bitmap. If I take out the lines for the rotate, _addCanvas will be drawn to the bitmap, but I need for _addCanvas to be rotated.

_addCanvas has children that include simple shapes (squares, circles, lines) and TextBoxes.

I've already tried calling Measure, and Arrange, and UpdateLayout on _addCanvas to no avail. It doesn't get in the bitmap if it's rotated.

Was it helpful?

Solution

The solution to my problem was to add the _addCanvas as a child of canvas after I had called canvas.Measure and canvas.Arrange.

I'm not 100% on why this was necessary, but here is why I think this worked: While debugging, I noticed that the canvas.ActualWidth and canvas.ActualHeight are zero before the calls to measure and arrange. I guess that in this scenario (having a Canvas that's a child of a Canvas), the RenderTransformOrigin for _addCanvas was being set relative to canvas. Since the ActualWidth and ActualHeight of canvas were both zero when I put _addCanvas in its list of children, _addCanvas was getting rotated about the origin, instead of about its center.

If you insert _addCanvas into the list of children after canvas has been measured and arranged, canvas will have non-zero values for ActualWidth and ActualHeight, and _addCanvas will be rotated about its center as desired.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top