Windows Phone 8.1 剪切图片

network | | 访问(42)
<ScrollViewer>
    <StackPanel>
        <Grid x:Name="LayoutRoot">
            <Image Source="/test.jpg"  Height="460" Width="300"  Name="image1"/>
        </Grid>
        <Button Content="剪切" x:Name="button"></Button>
        <Image  Name="image2" />
    </StackPanel>
</ScrollViewer>
public sealed partial class MainPage: Page {
    //Rectangle r;
    public MainPage() {
        this.InitializeComponent();
        button.Click += button_Click;
        SetPicture();
    }

    async void button_Click(object sender, RoutedEventArgs e) {
        ClipImage();
        var bitmap = new RenderTargetBitmap();
        await bitmap.RenderAsync(LayoutRoot);
        image2.Source = bitmap;
    }

    void SetPicture() {
        Rectangle rect = new Rectangle();
        rect.Opacity = 0.5;
        rect.Fill = new SolidColorBrush(Colors.White);
        rect.Height = image1.Height;
        rect.Width = image1.Width;
        rect.Stroke = new SolidColorBrush(Colors.Red);
        rect.StrokeThickness = 2;
        rect.Margin = image1.Margin;
        rect.ManipulationMode = ManipulationModes.All;
        rect.ManipulationDelta += rect_ManipulationDelta;

        LayoutRoot.Children.Add(rect);
        LayoutRoot.Height = image1.Height;
        LayoutRoot.Width = image1.Width;
    }

    void rect_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e) {
        Rectangle croppingRectangle = (Rectangle) sender;

        if (croppingRectangle.Width >= (int) e.Delta.Translation.X) croppingRectangle.Width -= (int) e.Delta.Translation.X;

        if (croppingRectangle.Height >= (int) e.Delta.Translation.Y) croppingRectangle.Height -= (int) e.Delta.Translation.Y;
    }

    void ClipImage() {
        RectangleGeometry geo = new RectangleGeometry();
        Rectangle r = (Rectangle)(from c in LayoutRoot.Children where c.Opacity == 0.5 select c).First();
        GeneralTransform gt = r.TransformToVisual(LayoutRoot);
        Point p = gt.TransformPoint(new Point(0, 0));
        geo.Rect = new Rect(p.X, p.Y, r.Width, r.Height);
        image1.Clip = geo;
        r.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
    }

    protected override void OnNavigatedTo(NavigationEventArgs e) {}
}