Crop image with dynamic rectangle coordinate

这一生的挚爱 提交于 2019-12-04 22:48:42
Xyroid

Using below code, rectangle would be in middle of screen and image can be panned. The content within rectangle will be clipped.

<Page.BottomAppBar>
    <AppBar IsSticky="True" IsOpen="True">
        <Button Content="Crop" Click="btnCrop_Click" />
    </AppBar>
</Page.BottomAppBar>

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
    <Image x:Name="photo" HorizontalAlignment="Center" VerticalAlignment="Center" ManipulationMode="All" Source="http://www.wired.com/reviews/wp-content/uploads/2012/10/Windows-8-1.jpg" />
    <Path x:Name="path" Stroke="Red" StrokeThickness="3" />
</Grid>
private CompositeTransform compositeTranslation;
RectangleGeometry rect = new RectangleGeometry();
public BlankPage4()
{
    this.InitializeComponent();
    rect.Rect = new Rect((Window.Current.Bounds.Width - 480) / 2, (Window.Current.Bounds.Height - 340) / 2, 480, 340);
    path.Data = rect;
}

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    photo.ManipulationDelta += Composite_ManipulationDelta;
    compositeTranslation = new CompositeTransform();
    photo.RenderTransform = this.compositeTranslation;
}

private void btnCrop_Click(object sender, RoutedEventArgs e)
{
    GeneralTransform gt = photo.TransformToVisual(null);
    Point pt = gt.TransformPoint(new Point(0, 0));
    var _rect = new RectangleGeometry();
    _rect.Rect = new Rect((rect.Bounds.X / compositeTranslation.ScaleX) - (pt.X / compositeTranslation.ScaleX), (rect.Bounds.Y / compositeTranslation.ScaleY) - (pt.Y / compositeTranslation.ScaleY), 480 / compositeTranslation.ScaleX, 340 / compositeTranslation.ScaleY);
    photo.Clip = _rect;
}

void Composite_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
{
    // scale the image.
    compositeTranslation.CenterX = photo.ActualWidth / 2;
    compositeTranslation.CenterY = photo.ActualHeight / 2;
    compositeTranslation.ScaleX *= e.Delta.Scale;
    compositeTranslation.ScaleY *= e.Delta.Scale;
    compositeTranslation.TranslateX += e.Delta.Translation.X;
    compositeTranslation.TranslateY += e.Delta.Translation.Y;
}

Updated: Code updated as told by Howard Hee solving the issue wherein zooming in/out will show only black screen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!