05. Image cropping for Windows Store app,

Source: Internet
Author: User

05. Image cropping for Windows Store app,

 

In the Win Phone Silverlight api, there is a PhotoChooserTask selector that specifies the width and height attributes. when selecting an image,

You can crop the data by using the following code:

PhotoChooserTask photoChooserTask = new PhotoChooserTask (); photoChooserTask. completed + = new EventHandler <PhotoResult> (photoChooserTask_Completed); // set the width and height of photoChooserTask. pixelHeight = 130; photoChooserTask. pixelWidth = 130; photoChooserTask. showCamera = true; photoChooserTask. show ();


After selecting an image, you can crop it:

 

 

This interaction is imitated here, and similar interaction is implemented in the Store app.

 

1. XAML page

1) first place two Image controls, one showing the user's scaling and translation gesture operations, and the other after the display is complete:

<Image  x:Name="img" Stretch="UniformToFill" ManipulationMode="All"  ManipulationDelta="Image_ManipulationDelta"  RenderTransformOrigin="0.5,0.5">    <Image.RenderTransform>        <CompositeTransform x:Name="img_transform" CenterX="0" CenterY="0"/>    </Image.RenderTransform></Image><Image x:Name="imgResult" Width="100" Height="100"/>

 

2) place a Border element. Its Border is black and transparent. The width and height in the middle are set to 200px, and a white Border is placed in it as the framing frame:

<! -- Screen mask --> <Border IsHitTestVisible = "False" x: name = "borderMask" BorderThickness = "135,268.3" Background = "Transparent" BorderBrush = "#55000000"> <Border BorderThickness = "1" BorderBrush = "White"/> </Border>

 

 

 

2. on the C # page

1) register the SizeChanged event of the current Page object to adjust the position of the mask and image when the width and height of Windows change:

// When the page layout changes, dynamically adjust the position of the mask this. SizeChanged + = PhotoChooserPage_SizeChanged;

 

Void PhotoChooserPage_SizeChanged (object sender, SizeChangedEventArgs e) {InitMask ();} // the width and height of the framing box. The initial minimum width and height of the img image control must be greater than its public double Img_w = 200; // The size of the framing box-used as the standard Rect measureRect; void InitMask () {double w = Window. current. bounds. width; double h = Window. current. bounds. height; if (w> Img_w & h> Img_w) {// left margin double left = (w-Img_w)/2; // top margin double top = (h-Img_w)/2; // The standard measureRect = new Rect (left, top, Img_w, Img_w) of the context box ); // set the Border of Border to black and translucent. if the background is null, the framing effect is borderMask. borderThickness = new Thickness (left, top, left, top); borderMask. width = w; borderMask. height = h; Canvas. setLeft (img, left); Canvas. setTop (img, top); Canvas. setLeft (imgResult, (w-imgResult. actualWidth)/2 );}}

 

2) In the Image_ManipulationDelta event of the Image control, adjust the stretching and scaling of the current Image:

// Scale and accumulate double scale = 1.0; // pan and accumulate double translate_x = 0; double translate_y = 0; object o = 1; private void Image_ManipulationDelta (object sender, ManipulationDeltaRoutedEventArgs e) {e. handled = true; lock (o) {// if (! E. isInertial) {// change the screen coordinate of x-y translate_x + = e. delta. translation. x; translate_y + = e. delta. translation. y; // scale * = e. delta. scale; // modify the image CompositeTransform object transform = translate_x; img_transform.TranslateY = translate_y; img_transform.ScaleX = img_transform.ScaleY = scale; // if it exceeds the context box, cancel the above modification if (! IsValide () {translate_x-= e. delta. translation. x; translate_y-= e. delta. translation. y; scale/= e. delta. scale; img_transform.TranslateX = translate_x; img_transform.TranslateY = translate_y; img_transform.ScaleX = img_transform.ScaleY = scale ;}}}}

 

3) Calculate the current image range and limit the image size and border to the following:

// Determine the middle position of the image in the mask bool IsValide () {Rect Temp = GetBounds (img, LayoutRoot); // find the current Windows. foundation. rect indicates the rectangle and specifies Windows. foundation. rect indicates the intersection of the rectangle and stores the result as current // Windows. foundation. rect Temp. intersect (measureRect); if (Temp = measureRect) {return true;} return false;} // obtain the coordinates and dimensions of the UIElement on the page public Rect GetBounds (FrameworkElement childElement, frameworkElement parentElement) {// https://msdn.microsoft.com/en-us/library/system.windows.media.visual.transformtovisual%28v=vs.110%29.aspx // https://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.uielement.transformtovisual.aspx GeneralTransform transform = childElement. transformToVisual (parentElement); return transform. transformBounds (new Rect (0, 0, childElement. actualWidth, childElement. actualHeight ));}


4) When you click the crop button, use BitmapEncoder to crop the image:

Private async void AppBarButton_Crop_Click (object sender, RoutedEventArgs e) {appBar. isEnabled = false; try {StorageFile sourceFile = PickedFile; // await Windows. applicationModel. package. current. installedLocation. getFileAsync ("Images \ test \ test.jpg"); if (PickedFile = null) return; using (var readStream = await sourceFile. openReadAsync () {var decoder = await BitmapDecoder. createAsync (readStre Am); // using (InMemoryRandomAccessStream writeStream = new InMemoryRandomAccessStream () // {if (WriteStream! = Null) {WriteStream. dispose ();} WriteStream = new InMemoryRandomAccessStream (); BitmapEncoder encoder = await BitmapEncoder. createForTranscodingAsync (WriteStream, decoder); Rect temp = GetBounds (img, LayoutRoot); double scale_x = decoder. pixelWidth/temp. width; encoder. bitmapTransform. bounds = new BitmapBounds {X = (uint) Math. round (measureRect. x-temp. x) * scale_x, 0), Y = (uint) Math. round (measureRect. y-temp. y) * scale_x, 0), Width = (uint) Math. round (measureRect. width * scale_x, 0), Height = (uint) Math. round (measureRect. height * scale_x, 0)}; await encoder. flushAsync (); BitmapImage bi = new BitmapImage (); bi. setSource (WriteStream); imgResult. source = bi; // if you need to set the fixed width and height of the image, you can use the WriteableBitmap object // WriteableBitmap wb = new WriteableBitmap (120,120); // wb. setSource (writeStream); // imgResult. source = wb; double size = WriteStream. size/(1024*1024.0); if (size> 5) await (new MessageDialog (string. format ("the image is larger than 5 MB (current {0: 0. 0} MB), select "))). showAsync (); // }}catch (Exception ex) {(new MessageDialog ("the region has exceeded the boundary:" + ex. message )). showAsync ();} appBar. isEnabled = true ;}

 


Display Results on Windows:

 

Display effects on mobile phones:

 

 

 

Demo download link

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.