Quantcast
Channel: WriteableBitmapEx
Viewing all 360 articles
Browse latest View live

New Post: How to draw text in WPF without WriteableBitmap constructor that takes UIElement parameter?

$
0
0
The samples and other discussions show a 3rd constructor that takes 2 parameters (UIElement, Transform) and it seems this is the only way recommended to achieve writing text to the bitmap.

Most samples and referred examples are in Silverlight, but I'm restricted to WPF client app environment. MSDN seems to show the WriteableBitmap constructor that takes the UIElement input is only supported on Silverlight.

Is there another recommendation to draw text that will work in WPF??

Thanks in advance.

New Post: How to draw text in WPF without WriteableBitmap constructor that takes UIElement parameter?

New Post: How to draw text in WPF without WriteableBitmap constructor that takes UIElement parameter?

$
0
0
Thanks for the quick response. It works using this approach, then blitting with my base WriteableBitmap.

On performance, I'm seeing ~600uS to create each label and cache it in a WriteableBitmap object. For my use case of ~100K items (1 item = rectangle and label), the time to create each and cache for subsequent blitting would be >55s which is too much. Is this the most performant text approach that I should expect? Would the Silverlight UIElement conversion take about the same time? Maybe this is just my wake up call that drawing text is expensive.

As for the blitting of a cached text bitmap into the base, the performance is quite reasonable averaging 720nS per-blit; thus 72ms for my 100K case, although I plan to only conditionally add the text if determined it will be readable.

Benchmark system: Core i7 Q740, 1.73Ghz, 8GB RAM, W7 x64

//-----------------------------------

To summarize my approach for others, given the performance seen:
  1. Create a WriteableBitmap for the text (created on-demand and cached for future repeated use)
    a) DrawingVisual's DrawingContext.DrawText (<FormattedText>, new Point(0,0))
    b) Use the bounds of the FormattedText object as the 'sourceRect'
    c) Convert the DrawingVisual to a RenderTargetBitmap using sourceRect from (b)
    d) Create a WriteableBitmap object dimensioned the same size as sourceRect
            FormattedText text = new FormattedText(displayLabel,
                new System.Globalization.CultureInfo("en-us"),
                FlowDirection.LeftToRight,
                new Typeface(new FontFamily("Arial"), FontStyles.Normal, FontWeights.Normal, new FontStretch()),
                12,
                Brushes.Black);

            DrawingVisual drawingVisual = new DrawingVisual();
            DrawingContext drawingContext = drawingVisual.RenderOpen();
            drawingContext.DrawText(text, new Point(0, 0));
            drawingContext.Close();


            Rect sourceRect = new Rect(0, 0, (int)text.Width, (int)text.Height);

            RenderTargetBitmap rtb = new RenderTargetBitmap((int)sourceRect.Width, (int)sourceRect.Height, 96, 96, PixelFormats.Pbgra32);
            rtb.Render(drawingVisual);

            LabelBitmapCache = BitmapFactory.New((int)sourceRect.Width, (int)sourceRect.Height);
            rtb.CopyPixels(new Int32Rect(0, 0, rtb.PixelWidth, rtb.PixelHeight), 
                            LabelBitmapCache.BackBuffer, 
                            LabelBitmapCache.BackBufferStride * LabelBitmapCache.PixelHeight, 
                            LabelBitmapCache.BackBufferStride);
  1. Conditionally blit the text cached WriteableBitmap with my base (if determined it will be readable - not shown)
_bmp.Blit(new Rect(left, 5, i.LabelBitmapCache.PixelWidth, i.LabelBitmapCache.PixelHeight), i.LabelBitmapCache, 
                                  new Rect(0,0,i.LabelVisual.ContentBounds.Width, i.LabelVisual.ContentBounds.Height));

New Post: How to draw text in WPF without WriteableBitmap constructor that takes UIElement parameter?

$
0
0
Continued experiments with the RenderTargetBitmap lead down a rat-hole of a seemingly well know memory issue that leads to crashes. I've not found a way out.

Are there any other ways to draw text using this library in WPF?

Created Unassigned: drawing outside the bitmap area causing clamps [20735]

$
0
0
hi,
when drawing any shape outside the bitmap area, lines/pixels are being clammed into the boundaries.
and causing the shape to look different.
for example draw an ellipse close to the edge, you will see the start of the ellipse and in the edge a vertical/horizontal line.

suggestion :
1-to have a IsClamp property , by setting to False (default is TRUE) it will not draw the "missing pixels on the edges.
2- override drawing methods for this.


currently the only way I've managed to "avoid" this is by creating the bitmap big enough
but then i had to crop it based on the drawing logic.

regards,
benny.

New Post: WriteableBitmap performance quirkyness

$
0
0
I initialize my WriteableBitmap some where at start of program (I call CreateWriteableBitmap())

When I run my program, I have an wpf Image on form, my theImage.Source = writeableBitmap

I receive a new buffer of image data from a camera, and update the writeableBitmap (see code below)
My original FPS(frames per second) was 32 FPS, but the image was not displaying properly
I originally created WriteableBitmap with PixelFormats.Bgr32 setting
I fixed it to correct format: PixelFormats.Gray16
The Image now displayed correctly
That is ONLY THING I changed.

My FPS dropped from 32 FPS to 16 FPS.
The size of the image did not change, just how it was to be interpreted.
This one change dropped frame rate in half.

My question is why??? (again size of image didn't change just this setting)

(see code below)
        public class NativeMethods
        {
            [DllImport("Kernel32.dll", EntryPoint = "RtlMoveMemory", SetLastError = false)]
            public static extern void CopyMemory(IntPtr dest, IntPtr src, int size);
        }

        static System.Windows.Media.Imaging.WriteableBitmap writeableBitmap;

        private void CreateWriteableBitmap()
        {
        ..... misc code .....
       
// FPS = 32 FPS
        original code --> writeableBitmap = new WriteableBitmap((int)width, (int)height, 96, 96, PixelFormats.Bgr32, null);


// FPS = 16 FPS
        fixed code    --> writeableBitmap = new WriteableBitmap((int)width, (int)height, 96, 96, PixelFormats.Gray16, null);

   theImage.Source = writeableBitmap;

        ..... misc code .....
        }


        private void UpdateImage(ImageArrivedArgs info)
        {
            int width = 1316;
            int height = 1312;
            int stride = width * (((int)BitsPerPixel + 7) / 8);

            byte[] data = info.data;

            GCHandle pinnedArray = GCHandle.Alloc(data, GCHandleType.Pinned);
            IntPtr ptr2Data = pinnedArray.AddrOfPinnedObject();

            writeableBitmap.Lock();

            // Copy the bitmap's data directly to the on-screen buffers
            NativeMethods.CopyMemory(writeableBitmap.BackBuffer, ptr2Data, width * height * 2);

            // Moves the back buffer to the front.
            writeableBitmap.AddDirtyRect(new Int32Rect(0, 0, width, height));
            writeableBitmap.Unlock();

            pinnedArray.Free();
        }

New Post: WriteableBitmap performance quirkyness

$
0
0
Well, that Gray format is not supported by hardware and involves that it's converted from color to gray. Most cameras support YCrCb or similar where you can just use the Y component for brightness value.

New Post: WriteableBitmap performance quirkyness

$
0
0
I had not even considered that aspect!!

Thank you for shedding light on that issue!

Commented Unassigned: Blit doesn't work well with transparent PNG images [20713]

$
0
0
Hello

I am trying to apply an transparent image (in png format) over background image. The result is not very good as applied image has too much artifacts over it.
It is known problem?

I am making an application for Windows 8.1 RT.

```
img.Blit(r, talisman, new Rect(0, 0, talisman.PixelWidth, talisman.PixelHeight));
```

Using WriteableBitmapExtensions.BlendMode.Alpha doesn't help at all. When I put both images i XAML one over another, I see no artifacts.
Comments: ** Comment from web user: lachlank **

I also found artefact bugs in Blit() with BlendMode = Alpha.

I changed the algorithm used in the Blit() method of WriteableBitmapBlitExtensions.cs to match that described in the [Alpha Compositing article on Wikipedia](http://en.wikipedia.org/wiki/Alpha_compositing), which works correctly. It is a simplistic implementation to prove the point and could of course be tidied up for performance, but proves the point and will make your code work:

```
double saX = (double)sa / 255;
double srX = (double)sr / 255;
double sgX = (double)sg / 255;
double sbX = (double)sb / 255;
double daX = (double)da / 255;
double drX = (double)dr / 255;
double dgX = (double)dg / 255;
double dbX = (double)db / 255;

var newAlphaX = (saX + (daX * (1.0 - saX)));
var newRedX = (srX * saX + (drX * daX * (1.0 - saX))) / newAlphaX;
var newGreenX = (sgX * saX + (dgX * daX * (1.0 - saX))) / newAlphaX;
var newBlueX = (sbX * saX + (dbX * daX * (1.0 - saX))) / newAlphaX;

var newAlpha = (int) (newAlphaX * 255.0);
var newRed = (int) (newRedX * 255.0);
var newGreen = (int)(newGreenX * 255.0);
var newBlue = (int)(newBlueX * 255.0);

destPixel = (newAlpha << 24) + (newRed << 16) + (newGreen << 8) + newBlue;
//destPixel = ((((sa << 8) + ((255 - sa) * da)) >> 8) << 24) +
// ((((sr << 8) + ((255 - sa) * dr)) >> 8) << 16) +
// ((((sg << 8) + ((255 - sa) * dg)) >> 8) << 8) +
// (((sb << 8) + ((255 - sa) * db)) >> 8);
// (((sb << 8) + ((255 - sa) * db)) >> 8);
```

Commented Unassigned: Blit doesn't work well with transparent PNG images [20713]

$
0
0
Hello

I am trying to apply an transparent image (in png format) over background image. The result is not very good as applied image has too much artifacts over it.
It is known problem?

I am making an application for Windows 8.1 RT.

```
img.Blit(r, talisman, new Rect(0, 0, talisman.PixelWidth, talisman.PixelHeight));
```

Using WriteableBitmapExtensions.BlendMode.Alpha doesn't help at all. When I put both images i XAML one over another, I see no artifacts.
Comments: ** Comment from web user: lachlank **

Have attached a patch for consideration:

```
var outAlpha = ((sa << 8) + ((255 - sa) * da)) >> 8;

destPixel = (outAlpha << 24) +
((((((sr * sa) << 8) + ((255 - sa) * dr * da)) >> 8) /outAlpha) << 16) +
((((((sg * sa) << 8) + ((255 - sa) * dg * da)) >> 8) /outAlpha) << 8) +
(((((sb * sa) << 8) + ((255 - sa) * db * da)) >> 8) / outAlpha);
```

Source code checked in, #106980

$
0
0
* The WP SaveToMediaLibrary extension now returns the created Picture instance. * Fixed the issue #20713 with the alpha blitting

Edited Issue: Blit doesn't work well with transparent PNG images [20713]

$
0
0
Hello

I am trying to apply an transparent image (in png format) over background image. The result is not very good as applied image has too much artifacts over it.
It is known problem?

I am making an application for Windows 8.1 RT.

```
img.Blit(r, talisman, new Rect(0, 0, talisman.PixelWidth, talisman.PixelHeight));
```

Using WriteableBitmapExtensions.BlendMode.Alpha doesn't help at all. When I put both images i XAML one over another, I see no artifacts.
Comments: ** Comment from web user: teichgraf **

Thanks Lachlan. The patch was committed in changeset 106980.

Updated Wiki: Home

$
0
0

Description

The WriteableBitmapEx library is a collection of extension methods for the WriteableBitmap. The WriteableBitmap class is available for Windows Phone, WPF, WinRT Windows Store XAML and Silverlight and allows the direct manipulation of a bitmap and could be used to generate fast procedural images by drawing directly to a bitmap. The WriteableBitmap API is very minimalistic and there's only the raw Pixels array for such operations. The WriteableBitmapEx library tries to compensate that with extensions methods that are easy to use like built in methods and offer GDI+ like functionality. The library extends the WriteableBitmap class with elementary and fast (2D drawing) functionality, conversion methods and functions to combine (blit) WriteableBitmaps.
The extension methods are grouped into different CS files with a partial class. It is possible to include just a few methods by using the specific source CS files directly or all extension methods through the built library assembly.

Available as NuGet package.

WriteableBitmapEx was also ported to Windows Embedded.

See the Issue Tracker for a list of features that will be added in the future.

wbx_announcement.png

Features

GDI+ like drawing functionality for the WriteableBitmap.
Support for Windows Phone Silverlight, desktop Silverlight, WPF and Windows WinRT XAML.
  • Base
    • Support for the Color structure (alpha premultiplication will be performed)
    • Also overloads for faster int32 as color (assumed to be already alpha premultiplied)
    • SetPixel method with various overloads
    • GetPixel method to get the pixel color at a specified x, y coordinate
    • Fast Clear methods
    • Fast Clone method to copy a WriteableBitmap
    • ForEach method to apply a given function to all pixels of the bitmap
  • Transformation
    • Crop method to extract a defined region
    • Resize method with support for bilinear interpolation and nearest neighbor
    • Rotate in 90° steps clockwise and any arbitrary angle
    • Flip vertical and horizontal
  • Shapes
    • Fast line drawing algorithms including an anti-aliased algorithm
    • Ellipse, polyline, quad, rectangle and triangle
    • Cubic Beziér, Cardinal spline and closed curves
  • Filled shapes
    • Fast ellipse and rectangle fill method
    • Polygon, triangle and quad
    • Beziér and Cardinal spline curves
  • Blitting
    • Different blend modes including alpha, additive, subtractive, multiply, mask and none
    • Optimized fast path for non blended blitting
  • Conversion
    • Convert a WriteableBitmap to a byte array
    • Create a WriteableBitmap from a byte array
    • Create a WriteableBitmap easily from the application resource or content
    • Create a WriteableBitmap from an any platform supported image stream
    • Write a WriteableBitmap as a TGA image to a stream
    • Separate extension method to save as a PNG image. Download here
  • Windows Phone specific methods
    • Save to media library and the camera roll

Live samples

Samples that come with the WriteableBitmapEx source code in action:
  • The Shapes sample includes various scenarios where different shapes are drawn. By default a little demo is shown called "Breathing Flower". Basically different sized circles rotating around a center ring are generated. The sample also contains a static page showing some of the possible shapes.
  • The Fill sample starts with a demo that animates the Cardinal spline's tension of the FillCurveClosed method, plus some random animated filled ellipses. The sample also contains a static page showing some of the possible filled shapes.
  • The Curve sample demonstrates the Beziér and Cardinal spline methods. The sample starts with a demo animation that uses the Cardinal spline DrawCurve method to draw an artificial plant that grows procedurally. The other part of the sample is interactive and allows to draw and manipulate Beziér and Cardinal splines with the mouse. See this blog post for further information.
  • The Blit sample combines WriteableBitmaps and shows a neat particle effect.
Video of the Windows Phone Interactive Curve Sample.

External resources:
Adam Kinney made a great sample that uses the WriteableBitmapEx library to dynamically apply a torn weathered effect to a photo.
Erik Klimczak from Calrity Consulting wrote a very good blog post about Advanced Animation: Animating 15,000 Visuals in Silverlight. He uses the WriteableBitmapEx to get the best performance.
Peter Bromberg wrote a great article called Silverlight 4 Martin Fractals with WriteableBitmapEx.

Performance!

The WriteableBitmapEx methods are much faster than the XAML Shape subclasses. For example, the WriteableBitmapEx line drawing approach is more than 20-30 times faster as the Silverlight Line element. So if a lot of shapes need to be drawn and anti-aliasing or other SIlverlight Shape properties are not needed, the WriteableBitmapEx methods are the right choice.

Easy to use!

// Initialize the WriteableBitmap with size 512x512 and set it as source of an Image control
WriteableBitmap writeableBmp = BitmapFactory.New(512, 512);
ImageControl.Source = writeableBmp;
writeableBmp.GetBitmapContext();

// Load an image from the calling Assembly's resources only by passing the relative path
writeableBmp = BitmapFactory.New(1, 1).FromResource("Data/flower2.png");

// Clear the WriteableBitmap with white color
writeableBmp.Clear(Colors.White);

// Set the pixel at P(10, 13) to black
writeableBmp.SetPixel(10, 13, Colors.Black);

// Get the color of the pixel at P(30, 43)
Color color = writeableBmp.GetPixel(30, 43);

// Green line from P1(1, 2) to P2(30, 40)
writeableBmp.DrawLine(1, 2, 30, 40, Colors.Green);

// Line from P1(1, 2) to P2(30, 40) using the fastest draw line method with the color as integerint[] pixels = writeableBmp.Pixels;
int w = writeableBmp.PixelWidth;
int h = writeableBmp.PixelHeight;
WriteableBitmapExtensions.DrawLine(pixels, w, h, 1, 2, 30, 40, myIntColor);

// Blue anti-aliased line from P1(10, 20) to P2(50, 70)
writeableBmp.DrawLineAa(10, 20, 50, 70, Colors.Blue);

// Black triangle with the points P1(10, 5), P2(20, 40) and P3(30, 10)
writeableBmp.DrawTriangle(10, 5, 20, 40, 30, 10, Colors.Black);

// Red rectangle from the point P1(2, 4) that is 10px wide and 6px high
writeableBmp.DrawRectangle(2, 4, 12, 10, Colors.Red);

// Filled blue ellipse with the center point P1(2, 2) that is 8px wide and 5px high
writeableBmp.FillEllipseCentered(2, 2, 8, 5, Colors.Blue);

// Closed green polyline with P1(10, 5), P2(20, 40), P3(30, 30) and P4(7, 8)int[] p = newint[] { 10, 5, 20, 40, 30, 30, 7, 8, 10, 5 };
writeableBmp.DrawPolyline(p, Colors.Green);

// Cubic Beziér curve from P1(5, 5) to P4(20, 7) with the control points P2(10, 15) and P3(15, 0)
writeableBmp.DrawBezier(5, 5, 10, 15, 15, 0, 20, 7,  Colors.Purple);

// Cardinal spline through the points P1(10, 5), P2(20, 40) and P3(30, 30) with a tension of 0.5int[] pts = newint[] { 10, 5, 20, 40, 30, 30};
writeableBmp.DrawCurve(pts, 0.5,  Colors.Yellow);

// A filled Cardinal spline through the points P1(10, 5), P2(20, 40) and P3(30, 30) with a tension of 0.5
writeableBmp.FillCurveClosed(pts, 0.5,  Colors.Green);

// Blit a bitmap using the additive blend mode at P1(10, 10)
writeableBmp.Blit(new Point(10, 10), bitmap, sourceRect, Colors.White, WriteableBitmapExtensions.BlendMode.Additive);

// Override all pixels with a function that changes the color based on the coordinate
writeableBmp.ForEach((x, y, color) => Color.FromArgb(color.A, (byte)(color.R / 2), (byte)(x * y), 100));

// Present the WriteableBitmap!
writeableBmp.Invalidate();

// Take snapshotvar clone = writeableBmp.Clone();

// Save to a TGA image stream (file for example)
writeableBmp.WriteTga(stream);

// Crops the WriteableBitmap to a region starting at P1(5, 8) and 10px wide and 10px highvar cropped = writeableBmp.Crop(5, 8, 10, 10);

// Rotates a copy of the WriteableBitmap 90 degress clockwise and returns the new copyvar rotated = writeableBmp.Rotate(90);

// Flips a copy of the WriteableBitmap around the horizontal axis and returns the new copyvar flipped = writeableBmp.Flip(FlipMode.Horizontal);

// Resizes the WriteableBitmap to 200px wide and 300px high using a bilinear interpolation methodvar resized = writeableBmp.Resize(200, 300, WriteableBitmapExtensions.Interpolation.Bilinear);

// Invalidate
writeableBmp.Dispose();

Additional Information

The WriteableBitmapEx library has its origin in several blog posts that also describe the implemenation and usage of some aspects in detail. The blog posts might be seen as the documentation.
WriteableBitmap Extension Methods introduced the SetPixel methods.
Drawing Lines - Silverlight WriteableBitmap Extensions II provided the DrawLine methods.
Drawing Shapes - Silverlight WriteableBitmap Extensions III brought the shape functionality (ellipse, polyline, quad, rectangle, triangle).
Convert, Encode And Decode Silverlight WriteableBitmap Data came with the byte array conversion methods and hows how to encode / decode a WriteableBitmap to JPEG.
Blitting and Blending with Silverlight’s WriteableBitmap provided the Blit functions.
WriteableBitmapEx - WriteableBitmap extensions now on CodePlex announced this project.
Quick and Dirty Output of WriteableBitmap as TGA Image provided the original TgaWrite function.
Rounder, Faster, Better - WriteableBitmapEx 0.9.0.0 announced version 0.9.0.0 and gives some further information about the curve sample.
Let it ring - WriteableBitmapEx for Windows Phone introtuced the WriteableBitmapEx version for the Windows Phone and a sample.
Filled To The Bursting Point - WriteableBitmapEx 0.9.5.0 announced version 0.9.5.0, has some information about the new Fill methods and comes with a nice sample.
One Bitmap to Rule Them All - WriteableBitmapEx for WinRT Metro Style announced version 1.0.0.0 and provides some background about the WinRT Metro Style version.

Support it

Donate

Credits

Bill Reiss wrote the Blit methods.
Nikola Mihaylov (Nokola) made some optimizations on the DrawLine and DrawRectangle methods, provided the original TgaWrite and the anti-aliased line drawing function.
Dr. Andrew Burnett-Thompson proposed the portability refactoring and WPF port.
Adam Kinney added some Blending modes to the Blit method.
Colin Eberhardt contributed the ForEach method.
Steve Hawley proposed an optimization of the Clear(Color) method.
Liam Bateman suggested the Color Keying BlendMode.
Mattias Fagerlund suggested the convolution method.
Wout de Zeeuw optimized the DrawLine method by 15%.
Lachlan Keown fixed a bug in the Blit alpha blending.
Your name here? We are always looking for valuable contributions.

René Schulte wrote all the rest and coordinates this project.

Ohloh statistics

Source code checked in, #106981

$
0
0
* Made BitmapContext thread-safe by using ConcurrentDictionary for ref counting

Edited Issue: Crash when using WriteableBitmapEx.Clear in parallel. [20005]

$
0
0
Using WriteableBitmapEx 1.0.8.0 from NuGet, I have some code where I'm creating a bunch of images in parrel. However, inside BitmapContext there's a static Dictionary used in the ctor - which leads to crashes when calling methods such as WriteableBitmapExtensions.Clear on different images concurrently.

Here's some code to reproduce the problem

```
Parallel.For(0, 1000, i =>
{
var bitmap = new WriteableBitmap(100, 100, 96, 96, PixelFormats.Gray16, null);
var converted = BitmapFactory.ConvertToPbgra32Format(bitmap);
converted.Clear(Colors.Aqua);
});
```
Comments: ** Comment from web user: teichgraf **

Fixed in 106981 by using ConcurrentDictionary for ref counting


Edited Issue: BitmapContext not thread safe [20143]

$
0
0
It seems the dictionaries used in the context class have some thread racing occurring when you have multiple WPF render threads (with own dispatchers). Some locks should fix it.
Comments: ** Comment from web user: teichgraf **

Fixed in 106981 by using ConcurrentDictionary for ref counting

New Post: draw ellipses vs blit

$
0
0
hi,
i need to draw the same shape(ellipse) 1 milion times on screen.
i was thinking on drawing once and blitting 1m - 1...
does anyone has any thoughts about this or suggest better approach ?
regards,
benny.

Source code checked in, #107028

$
0
0
* Rolled back wrong Blit changes. * Fixed a bug in WriteTga and Resizeso its paid attention to pre-mulitplied ARGB

New Post: Blit not producing anticipated results

$
0
0
I'm using the Blit method for image annotation functionality in a Windows Store app. Essentially the user takes a picture and is able to use the Windows.UI.Input.Inking.InkManager to draw on the picture (e.g. circles, boxes, etc). I'm then using the Blit method to combine the picture the user took with the annotation produced by the InkManager. The problem is that the combined saved image has the mark up from the InkManager appearing horizontally offset.

See https://onedrive.live.com/?cid=c21327df8f57089d#cid=C21327DF8F57089D&id=C21327DF8F57089D%21157 for examples of the original and saved (blitted) image.

The code to save the blitted images:
private async Task SaveMergedImages()
        {
            //Image foreground
            Windows.UI.Xaml.Media.Imaging.WriteableBitmap foregroundBmp;
            using (var a = new InMemoryRandomAccessStream())
            {
                //CurrentManager is a Windows.UI.Input.Inking.InkManager
                await CurrentManager.SaveAsync(a);

                a.Seek(0);
                foregroundBmp = await new Windows.UI.Xaml.Media.Imaging.WriteableBitmap(Convert.ToInt32(CurrentManager.BoundingRect.Width), Convert.ToInt32(CurrentManager.BoundingRect.Height)).FromStream(a);
            }

            Windows.UI.Xaml.Media.Imaging.WriteableBitmap backgroundBmp = null;
            using (var ims = new InMemoryRandomAccessStream())
            {
                using (var dataWriter = new DataWriter(ims))
                {
                    //ViewModel.ImageByteArrayToBeEdited is a byte[] of the image thats going to be edited
                    dataWriter.WriteBytes(ViewModel.ImageByteArrayToBeEdited);
                    await dataWriter.StoreAsync();

                    backgroundBmp = new Windows.UI.Xaml.Media.Imaging.WriteableBitmap(ViewModel.ImageToBeEdited.PixelWidth, ViewModel.ImageToBeEdited.PixelHeight);
                    ims.Seek(0);

                    //set the source of the in memory bmp as blit relies upon the SourceURI
                    await backgroundBmp.SetSourceAsync(ims);
                }
            }

            //merge 'em!
            backgroundBmp.Blit(
                new Rect(CurrentManager.BoundingRect.X, CurrentManager.BoundingRect.Y, foregroundBmp.PixelWidth, foregroundBmp.PixelHeight),
                foregroundBmp,
                new Rect(0, 0, foregroundBmp.PixelWidth, foregroundBmp.PixelHeight),
                WriteableBitmapExtensions.BlendMode.Alpha);

            await backgroundBmp.SaveToFile();
        }
This is all being done on a XAML page that has a Canvas with the canvas Background set to an ImageBrush.
//Windows.UI.Xaml.Controls.Canvas
            InkCanvas.Background = new ImageBrush()
            {
                ImageSource = ViewModel.ImageToBeEdited,
                Stretch = Stretch.Uniform
            };
I've tried various tweaks to the code, including changing the Stretch of the ImageBrush and multiple variations Rect params of the Blit method. None have worked. Please help.

New Post: Blit not producing anticipated results

$
0
0
Looks like the overlay has a different size. It needs to have the same width and height. The Blit does not scale. You can use the Resize method for that.
  • Rene
Viewing all 360 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>