问题
I have been struggling for two weeks for this problem . I am applying dragging and scaling to an image inside canvas.Dragging works fine and is limiting inside canvas IsBoundary functions but when I am applying scaling its drag area changes . If increases scaling with mouse drag area increases also and whem I make it shrink in size drag area also shrinks.Help me to solve this problem of limiting scaling Thanks. Here is my code link sample
回答1:
I think I understand your question. When you scale an item in a canvas the translation needs to account for the change in scale. Is that right?
Assuming this XAML:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Border Width="500"
Height="500"
BorderBrush="White"
BorderThickness="1">
<Canvas x:Name="MyCanvas">
<Rectangle x:Name="MyRectangle"
Width="50"
Height="50"
Fill="CornflowerBlue">
<Rectangle.RenderTransform>
<CompositeTransform TranslateX="225" TranslateY="225" />
</Rectangle.RenderTransform>
</Rectangle>
</Canvas>
</Border>
</Grid>
Try this code-behind:
void MainPage_Loaded(object sender, RoutedEventArgs args)
{
MyRectangle.ManipulationMode =
ManipulationModes.TranslateX
| ManipulationModes.TranslateY;
var transform = MyRectangle.RenderTransform as CompositeTransform;
var reposition = new Action<double, double>((x, y) =>
{
var size = new Size(MyRectangle.ActualWidth * transform.ScaleX, MyRectangle.ActualHeight * transform.ScaleY);
var location = MyRectangle.TransformToVisual(MyRectangle).TransformPoint(new Point(0, 0));
var minX = -location.X;
var maxX = MyCanvas.ActualWidth - size.Width;
var newX = Within(x, minX, maxX);
transform.TranslateX = Within(newX, minX, maxX);
var minY = -location.Y;
var maxY = MyCanvas.ActualHeight - size.Height;
var newY = Within(y, minY, maxX);
transform.TranslateY = Within(newY, minY, maxY);
});
MyRectangle.ManipulationDelta += (s, e) =>
{
var newX = transform.TranslateX + e.Delta.Translation.X;
var newY = transform.TranslateY + e.Delta.Translation.Y;
reposition(newX, newY);
};
MyRectangle.PointerWheelChanged += (s, e) =>
{
// require control
if (Window.Current.CoreWindow.GetKeyState(VirtualKey.Control)
== Windows.UI.Core.CoreVirtualKeyStates.None)
return;
// ignore horizontal
var props = e.GetCurrentPoint(MyRectangle).Properties;
if (props.IsHorizontalMouseWheel)
return;
// apply scale
var newScale = transform.ScaleX + (double)props.MouseWheelDelta * .001;
transform.ScaleX = transform.ScaleY = newScale;
// reposition
reposition(transform.TranslateX, transform.TranslateY);
};
}
public double Within(double value, double min, double max)
{
if (value <= min)
return min;
else if (value >= max)
return max;
else
return value;
}
I hope this helps.
Note: Since I am not on a touch machine right now, I implemented the mouse wheel to scale. But you can modify the code as you want. The logic would be identical.
Best of luck!
来源:https://stackoverflow.com/questions/23996120/how-to-limit-transformation-of-images-inside-canvas-in-window-store-app