Bitmap > Bitmap for Silverlight Quick Start > Step 3 of 4: Adding Code for Image Cropping |
The code in this step will load the default image and allow the user to crop it. Follow these steps:
C# |
Copy Code
|
---|---|
using C1.Silverlight; using C1.Silverlight.Imaging; using System.IO; |
C# |
Copy Code
|
---|---|
public partial class MainPage : UserControl { C1Bitmap bitmap = new C1Bitmap(); Rect selection; public MainPage() { InitializeComponent(); LoadDefaultImage(); image.Source = bitmap.ImageSource; var mouseHelper = new C1MouseHelper(imageGrid); mouseHelper.MouseDragStart += OnDrag; mouseHelper.MouseDragMove += OnDrag; } void OnDrag(object sender, MouseDragEventArgs e) { var transform = Application.Current.RootVisual.TransformToVisual(image); var start = transform.Transform(e.StartPosition); var end = transform.Transform(e.CurrentPosition); start.X = Math.Min(Math.Max(start.X, 0), bitmap.Width); end.X = Math.Min(Math.Max(end.X, 0), bitmap.Width); start.Y = Math.Min(Math.Max(start.Y, 0), bitmap.Height); end.Y = Math.Min(Math.Max(end.Y, 0), bitmap.Height); selection = new Rect(new Point( Math.Round(Math.Min(start.X, end.X)), Math.Round(Math.Min(start.Y, end.Y))), new Size(Math.Round(Math.Abs(start.X - end.X)), Math.Round(Math.Abs(start.Y - end.Y)))); UpdateMask(); } void UpdateMask() { topMask.Height = selection.Top; bottomMask.Height = bitmap.Height - selection.Bottom; leftMask.Width = selection.Left; rightMask.Width = bitmap.Width - selection.Right; } void LoadDefaultImage() { LoadImageStream(Application.GetResourceStream(new Uri("/SilverlightApplication3;component/Lenna.jpg", UriKind.Relative)).Stream); } void LoadImageStream(Stream stream) { bitmap.SetStream(stream); imageGrid.Width = bitmap.Width; imageGrid.Height = bitmap.Height; selection = new Rect(0, 0, bitmap.Width, bitmap.Height); UpdateMask(); } } |
In the next step you will run the application.