裁剪图像与矩形

时间:2013-10-06 14:17:29

标签: windows-8 windows-runtime microsoft-metro windows-store-apps winrt-xaml

我有一个图像,我想通过使用矩形来裁剪它,下面的代码是我放置图像并在图像中间绘制一个矩形的代码:

MainPage.xaml中:

<Canvas x:Name="canvas" HorizontalAlignment="Center" VerticalAlignment="Center" Width="340" Height="480" Background="Blue">
        <Image x:Name="photo" HorizontalAlignment="Center" VerticalAlignment="Center" ManipulationMode="All">
            <Image.RenderTransform>
                <CompositeTransform/>
            </Image.RenderTransform>
        </Image>
        <Path Stroke="Black" StrokeThickness="1">
            <Path.Data>
                <RectangleGeometry Rect="0,0,340,480"/>
            </Path.Data>
        </Path>
    </Canvas>

我成功显示图像并绘制一个矩形。示例图片如下: enter image description here

现在我想点击一个按钮来裁剪矩形内的图像(不是自动剪辑)。加载图像时自动添加矩形。所以不能使用“Point Pressed”和“Point Released”。而且也不能使用“rectangle.clip”因为它会自动剪辑图像。我该如何解决?感谢

更新 我能够移动图像,如何绑定数据并将矩形坐标设置为动态?下面的代码是转换图像。感谢。

public sealed partial class MainPage: Page
{
        private CompositeTransform compositeTranslation;

        public MainPage()
        {
            this.InitializeComponent();
            photo.ManipulationDelta += Composite_ManipulationDelta;
            compositeTranslation = new CompositeTransform();
            photo.RenderTransform = this.compositeTranslation;
        }

        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;
        }
}

1 个答案:

答案 0 :(得分:3)

我没有使用过XAML,因为它给我带来了困惑。所以我根据你的问题创建了一个片段。试试看,让我知道结果。我使用了与您发布的图像相同的图像

XAML

<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://i.stack.imgur.com/UIBSp.png" />
    <Path x:Name="path" Stroke="Red" StrokeThickness="3">
        <Path.Data>
            <RectangleGeometry Rect="545,212,440,420"/>
        </Path.Data>
    </Path>
</Grid>

C#

private void btnCrop_Click(object sender, RoutedEventArgs e)
{
    var _rect = new RectangleGeometry();
    _rect.Rect = path.Data.Bounds;
    photo.Clip = _rect;
}