Matthew
Matthew

Reputation: 4056

How to Place Border Around a Picture

In a page I display a picture that I receive from CameraCapureTask in the View

<Grid x:Name="EditPageGrid" Margin="{Binding}">
    <Grid Name="ViewportContainer" Margin="12,0,12,24">
        <Image x:Name="Viewport" LayoutUpdated="Viewport_LayoutUpdated" 
               Source="{Binding}"/>
    </Grid>
</Grid>

And I wish to be able to place a border around this image. How would it be possible to do this? I was thinking perhaps on a click event of some sort a border could be toggled on or off, but actually applying a border is where I am at a loss.

Upvotes: 0

Views: 1902

Answers (2)

Romasz
Romasz

Reputation: 29792

I figured out such an event: (probably there is better method, but this also works)

  private void Viewport_Tap(object sender, System.Windows.Input.GestureEventArgs e)
  {
     int imageHeight = (Viewport.Source as BitmapImage).PixelHeight;
     int imageWidth = (Viewport.Source as BitmapImage).PixelWidth;

     Canvas myCanvas = new Canvas();
     Rectangle myBorder = new Rectangle();
     myBorder.Width = imageWidth;
     myBorder.Height = imageHeight;
     myBorder.Stroke = new SolidColorBrush(Colors.Red);
     myBorder.StrokeThickness = 10;

     Image toBorder = new Image();
     toBorder.Source = Viewport.Source as BitmapImage;

     myCanvas.Children.Add(toBorder);
     myCanvas.Children.Add(myBorder);

     WriteableBitmap newImage = new WriteableBitmap(myCanvas, null);

     //Viewport.Source = newImage; - you can use this but watch out that Viewport.Source now is not BitmapImage
     //Below is one method how to make it BitmapImage
     //You can of course save newImage to file or whatever you want
     //You can also unsubscribe this event to prevent it from second tap which will cause Exception at first line (BitmaImage != WriteableBitmap)

     MemoryStream memoryStream = new MemoryStream();
     newImage.SaveJpeg(memoryStream, imageWidth, imageHeight, 0, 100);
     BitmapImage newBitmap = new BitmapImage();
     newBitmap.SetSource(memoryStream);

     Viewport.Source = newBitmap;
  }

Playing with this memory stream isn't good, but I've not known what you are planning to do with your new Bitmap.
As I've said - it's only example and I'm sure better methods exist (which I don't know). Hope this helps.

Upvotes: 0

Dweeberly
Dweeberly

Reputation: 4777

You can contain the image in a Border, like this:

<Grid x:Name="EditPageGrid" Margin="{Binding}">
    <Grid Name="ViewportContainer" Margin="12,0,12,24">
        <Border HorizontalAlignment="Center" BorderThickness="4" BorderBrush="Red">        
           <Image Source="C:\Users\Public\Pictures\Sample Pictures\Jellyfish.jpg"/>
        </Border>
    </Grid>
</Grid>

Upvotes: 2

Related Questions