Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
The ImageCropper Control allows user to freely crop an image.
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Page x:Class="ImageCropperExperiment.Samples.ImageCropperSample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="using:CommunityToolkit.WinUI.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="using:ImageCropperExperiment.Samples"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid RowSpacing="24">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<controls:ImageCropper x:Name="imageCropper"
Width="520"
Height="520"
AspectRatio="{x:Bind local:ImageCropperSample.ConvertStringToAspectRatio(AspectRatioSetting), Mode=OneWay}"
CropShape="{x:Bind local:ImageCropperSample.ConvertStringToCropShape(CropShapeSetting), Mode=OneWay}"
ThumbPlacement="{x:Bind local:ImageCropperSample.ConvertStringToThumbPlacement(ThumbPlacementSetting), Mode=OneWay}" />
<StackPanel Grid.Row="1"
HorizontalAlignment="Center"
Orientation="Horizontal"
Spacing="8">
<Button Click="PickButton_Click"
Content="Pick image"
Style="{StaticResource AccentButtonStyle}" />
<Button Click="SaveButton_Click"
Content="Save"
Style="{StaticResource AccentButtonStyle}" />
<Button Click="ResetButton_Click"
Content="Reset"
Style="{StaticResource AccentButtonStyle}" />
</StackPanel>
</Grid>
</Page>
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using CommunityToolkit.WinUI.Controls;
using Windows.Storage;
using Windows.Storage.Pickers;
namespace ImageCropperExperiment.Samples;
[ToolkitSampleMultiChoiceOption("ThumbPlacementSetting", "All", "Corners", Title = "Thumb Placement")]
[ToolkitSampleMultiChoiceOption("CropShapeSetting", "Rectangular", "Circular", Title = "Crop Shape")]
[ToolkitSampleMultiChoiceOption("AspectRatioSetting", "Custom", "Square", "Landscape(16:9)", "Portrait(9:16)", "4:3", "3:2", Title = "Aspect Ratio")]
[ToolkitSample(id: nameof(ImageCropperSample), "ImageCropper", description: $"A sample for showing how to create and use a {nameof(ImageCropper)}.")]
public sealed partial class ImageCropperSample : Page
{
public ImageCropperSample()
{
this.InitializeComponent();
_ = Load();
}
private async Task Load()
{
var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Owl.jpg"));
await imageCropper.LoadImageFromFile(file);
}
private async Task PickImage()
{
var filePicker = new FileOpenPicker
{
ViewMode = PickerViewMode.Thumbnail,
SuggestedStartLocation = PickerLocationId.PicturesLibrary,
FileTypeFilter =
{
".png", ".jpg", ".jpeg"
}
};
var file = await filePicker.PickSingleFileAsync();
if (file != null && imageCropper != null)
{
await imageCropper.LoadImageFromFile(file);
}
}
private async Task SaveCroppedImage()
{
var savePicker = new FileSavePicker
{
SuggestedStartLocation = PickerLocationId.PicturesLibrary,
SuggestedFileName = "Cropped_Image",
FileTypeChoices =
{
{ "PNG Picture", new List<string> { ".png" } },
{ "JPEG Picture", new List<string> { ".jpg" } }
}
};
var imageFile = await savePicker.PickSaveFileAsync();
if (imageFile != null)
{
BitmapFileFormat bitmapFileFormat;
switch (imageFile.FileType.ToLower())
{
case ".png":
bitmapFileFormat = BitmapFileFormat.Png;
break;
case ".jpg":
bitmapFileFormat = BitmapFileFormat.Jpeg;
break;
default:
bitmapFileFormat = BitmapFileFormat.Png;
break;
}
using (var fileStream = await imageFile.OpenAsync(FileAccessMode.ReadWrite, StorageOpenOptions.None))
{
await imageCropper.SaveAsync(fileStream, bitmapFileFormat);
}
}
}
public static ThumbPlacement ConvertStringToThumbPlacement(string placement) => placement switch
{
"All" => ThumbPlacement.All,
"Corners" => ThumbPlacement.Corners,
_ => throw new System.NotImplementedException(),
};
public static CropShape ConvertStringToCropShape(string cropshape) => cropshape switch
{
"Circular" => CropShape.Circular,
"Rectangular" => CropShape.Rectangular,
_ => throw new System.NotImplementedException(),
};
public static double? ConvertStringToAspectRatio(string ratio) => ratio switch
{
"Custom" => null,
"Square" => 1,
"Landscape(16:9)" => 16d / 9d,
"Portrait(9:16)" => 9d / 16d,
"4:3" => 4d / 3d,
"3:2" => 3d / 2d,
_ => throw new System.NotImplementedException(),
};
private async void PickButton_Click(object sender, RoutedEventArgs e)
{
await PickImage();
}
private async void SaveButton_Click(object sender, RoutedEventArgs e)
{
await SaveCroppedImage();
}
private void ResetButton_Click(object sender, RoutedEventArgs e)
{
imageCropper.Reset();
}
}
Syntax
<Page ...
xmlns:controls="using:CommunityToolkit.WinUI.Controls"/>
<controls:ImageCropper x:Name="ImageCropper" />
</Page>
Basic usage
You can set the cropped image source by using the LoadImageFromFile(StorageFile) method or setting the Source property.
//Load an image.
await ImageCropper.LoadImageFromFile(file);
//Another way to load an image.
ImageCropper.Source = writeableBitmap;
//Saves the cropped image to a stream.
using (var fileStream = await someFile.OpenAsync(FileAccessMode.ReadWrite, StorageOpenOptions.None))
{
await _imageCropper.SaveAsync(fileStream, BitmapFileFormat.Png);
}
Use Circular ImageCropper
You can set CropShape property to use the circular ImageCropper.
ImageCropper.CropShape = CropShape.Circular;
Change Aspect Ratio
You can set AspectRatio property to change the aspect ratio of the cropped image.
ImageCropper.AspectRatio = 16d / 9d;
Or you can crop image without aspect ratio.
ImageCropper.AspectRatio = null;
With an Overlay
The crop area can be overlaid with a brush. Here we use a RadialGradientBrush, but you can use any brush; backdrop Media brushes, Geometry brushes, bitmap and image brushes, and so on.
<Page x:Class="ImageCropperExperiment.Samples.ImageCropperOverlaySample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="using:CommunityToolkit.WinUI.Controls"
xmlns:local="using:ImageCropperExperiment.Samples"
xmlns:media="using:Microsoft.UI.Xaml.Media">
<Grid>
<controls:ImageCropper x:Name="ImageCropper"
Width="520"
Height="520"
AspectRatio="{x:Bind local:ImageCropperSample.ConvertStringToAspectRatio(AspectRatioSetting), Mode=OneWay}"
CropShape="{x:Bind local:ImageCropperSample.ConvertStringToCropShape(CropShapeSetting), Mode=OneWay}"
ThumbPlacement="{x:Bind local:ImageCropperSample.ConvertStringToThumbPlacement(ThumbPlacementSetting), Mode=OneWay}">
<controls:ImageCropper.Overlay>
<media:RadialGradientBrush>
<GradientStop Offset="0.75" Color="Transparent" />
<GradientStop Offset="1" Color="DimGray" />
</media:RadialGradientBrush>
</controls:ImageCropper.Overlay>
</controls:ImageCropper>
</Grid>
</Page>
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Windows.Storage;
namespace ImageCropperExperiment.Samples;
[ToolkitSampleMultiChoiceOption("ThumbPlacementSetting", "All", "Corners", Title = "Thumb Placement")]
[ToolkitSampleMultiChoiceOption("CropShapeSetting", "Circular", "Rectangular", Title = "Crop Shape")]
[ToolkitSampleMultiChoiceOption("AspectRatioSetting", "Custom", "Square", "Landscape(16:9)", "Portrait(9:16)", "4:3", "3:2", Title = "Aspect Ratio")]
[ToolkitSample(id: nameof(ImageCropperOverlaySample), "ImageCropper Overlay", description: $"A sample for showing how to use the overlay feature of {nameof(ImageCropper)}.")]
public sealed partial class ImageCropperOverlaySample : Page
{
public ImageCropperOverlaySample()
{
this.InitializeComponent();
_ = Load();
}
private async Task Load()
{
var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Owl.jpg"));
await ImageCropper.LoadImageFromFile(file);
}
}
Windows Community Toolkit