搜尋此網誌

2009年11月4日 星期三

Silverlight:簡單的3D屬性控制(RotationX、Y、Z))

開啟一個Silverlight專案(C#)後,在.xaml檔加入以下內容,產生一個Grid(即將以下內容整個放在<UserControl>及</UserControl>之間):


   <Grid x:Name="LayoutRoot" Width="450" Height="450" >
        <Canvas Background="Red" x:Name="canvasTop"
                MouseLeftButtonDown="getMousePosition" MouseMove="mouseMove" MouseLeave="unmouseDown" MouseLeftButtonUp="unmouseDown">
            <Ellipse x:Name="MyAnimatedRectangle" Stroke="Black" StrokeThickness="1"
                     Width="50" Height="50" >
                <Ellipse.Projection>
                    <PlaneProjection x:Name="pProject" RotationX="0" RotationY="0"/>
                </Ellipse.Projection>
                <Ellipse.RenderTransform>
                    <TranslateTransform X="200" Y="200"/>
                </Ellipse.RenderTransform>
                <Ellipse.Fill>
                    <LinearGradientBrush EndPoint="0.2,1" StartPoint="0.5,0">
                        <GradientStop Color="Black" Offset="0"/>
                        <GradientStop Color="#FFEEC5C5" Offset="1"/>
                    </LinearGradientBrush>
                </Ellipse.Fill>
            </Ellipse>
        </Canvas>
    </Grid>



上述的xaml內容,在名為canvasTop的Canvas元件中有四個mouse事件,即「MouseLeftButtomDown」、「MouseLeftButtonUp」、「MouseMove」、「MouseLeave」。事件發生時觸發的function:

MouseLeftButtomDown → getMousePosition()
MouseLeftButtonUp、MouseLeave → unmouseDown()
MouseMove → mouseMove()

與其對應的 .cs檔,程式內容如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Rotation3D_OnMouse
{
public partial class MainPage : UserControl
{
bool onMouseDown = false;//if mouse click on canvas
Point currentPosition;
Point nextPosition;

public MainPage()
{
InitializeComponent();
}

private void getMousePosition(object sender, MouseButtonEventArgs e)
{
onMouseDown = true;
currentPosition = e.GetPosition(canvasTop);
}

private void mouseMove(object sender, MouseEventArgs e)
{
if (!onMouseDown) return;

nextPosition = e.GetPosition(canvasTop);
PlaneProjection pp = MyAnimatedRectangle.Projection as PlaneProjection;
double tmpX = nextPosition.Y - currentPosition.Y;
double tmpY = nextPosition.X - currentPosition.X;
pp.RotationX = tmpX;
pp.RotationY = tmpY;
}

private void unmouseDown(object sender, MouseEventArgs e)
{
onMouseDown = false;
}
}
}



觸發MouseLeftButtonDown後做MouseMove的動作,可對Silverlight目標物件做RotationX、RotationZ的動作。

沒有留言:

張貼留言