WPF中图像控件Image的变换属性Transform:
即要想实现图片的平移、缩放、旋转,是修改它所在的Image控件的Transform变换属性。
下面在XAML中定义了Image图片的Transform属性。
<Image>
<Image.RenderTransform>
<TransformGroup>
<TranslateTransform/>
<ScaleTransform/>
<RotateTransform/>
</TransformGroup>
</Image.RenderTransform>
</Image>
图像平移:
按住鼠标左键,拖拽移动图片;松开鼠标左键,完成图像平移。
MVVM将鼠标事件绑定命令Command后在控制层处理。
private Image movingObject;
private Point StartPosition;
private Point EndPosition;
private void MouseLeftButtonDownCommand(object[] p)
{
object sender = p[0];
MouseButtonEventArgs e = p[1] as MouseButtonEventArgs;
Image img = sender as Image;
movingObject = img;
StartPosition = e.GetPosition(img);
}
private void MouseMoveCommand(object[] p)
{
object sender = p[0];
MouseEventArgs e = p[1] as MouseEventArgs;
Image img = sender as Image;
if (e.LeftButton == MouseButtonState.Pressed && sender == movingObject)
{
EndPosition = e.GetPosition(img);
TransformGroup tg = img.RenderTransform as TransformGroup;
var tgnew = tg.CloneCurrentValue();
if (tgnew != null)
{
TranslateTransform tt = tgnew.Children[0] as TranslateTransform;
var X = EndPosition.X - StartPosition.X;
var Y = EndPosition.Y - StartPosition.Y;
tt.X += X;
tt.Y += Y;
}
img.RenderTransform = tgnew;
}
}
private void MouseLeftButtonUpCommand(object[] p)
{
object sender = p[0];
MouseButtonEventArgs e = p[1] as MouseButtonEventArgs;
Image img = sender as Image;
movingObject = null;
}
图像缩放:
界面上准备两个按钮,点击分别实现图像的放大和缩小。
public void ZoomIn(Image img)
{
TransformGroup tg = img.RenderTransform as TransformGroup;
var tgnew = tg.CloneCurrentValue();
if (tgnew != null)
{
ScaleTransform st = tgnew.Children[1] as ScaleTransform;
img.RenderTransformOrigin = new Point(0.5, 0.5);
if (st.ScaleX > 0 && st.ScaleX <= 2.0)
{
st.ScaleX += 0.05;
st.ScaleY += 0.05;
}
else if (st.ScaleX < 0 && st.ScaleX >= -2.0)
{
st.ScaleX -= 0.05;
st.ScaleY += 0.05;
}
}
img.RenderTransform = tgnew;
}
public void ZoomOut(Image img)
{
TransformGroup tg = img.RenderTransform as TransformGroup;
var tgnew = tg.CloneCurrentValue();
if (tgnew != null)
{
ScaleTransform st = tgnew.Children[1] as ScaleTransform;
img.RenderTransformOrigin = new Point(0.5, 0.5);
if (st.ScaleX >= 0.2)
{
st.ScaleX -= 0.05;
st.ScaleY -= 0.05;
}
else if (st.ScaleX <= -0.2)
{
st.ScaleX += 0.05;
st.ScaleY -= 0.05;
}
}
img.RenderTransform = tgnew;
}
图像旋转:
界面上准备两个按钮,点击分别实现图像的左转和右转。
public void RotateLeft(Image img)
{
TransformGroup tg = img.RenderTransform as TransformGroup;
var tgnew = tg.CloneCurrentValue();
if (tgnew != null)
{
RotateTransform rt = tgnew.Children[2] as RotateTransform;
img.RenderTransformOrigin = new Point(0.5, 0.5);
rt.Angle -= 5;
}
img.RenderTransform = tgnew;
}
public void RotateRight(Image img)
{
TransformGroup tg = img.RenderTransform as TransformGroup;
var tgnew = tg.CloneCurrentValue();
if (tgnew != null)
{
RotateTransform rt = tgnew.Children[2] as RotateTransform;
img.RenderTransformOrigin = new Point(0.5, 0.5);
rt.Angle += 5;
}
img.RenderTransform = tgnew;
}
|
请发表评论