搜尋此網誌

2010年1月17日 星期日

Silverlight:Image U,V  -- Part 1

一般來說的「取U、V」軸,指的是說取圖片上某一範圍。例如橫軸取 0~0.5、縱軸取0~0.5,相當於顯示圖片左上角四分之一。在Silverlight上可以使用 Clip 來完成取U、V軸的動作。
另一方面,在自動調整內容大小,由最簡單的地方開始,指定某單位數量的"*"至Colunm或Row的寬高上,Silverlight內容即可依瀏覽器大小自動調整。

將以下程式碼寫入UserControl:

<Grid x:Name="LayoutRoot" Background="Gray"
  MouseLeftButtonUp="onRectUp" MouseLeave="onLeave">
 <Rectangle Stroke="Black" StrokeThickness="5"/>
 <Grid ShowGridLines="True">
  <Grid.ColumnDefinitions>
  <ColumnDefinition Width="1*"/>
  <ColumnDefinition Width="5*" MinWidth="200"/>
  <ColumnDefinition Width="1*"/>
 </Grid.ColumnDefinitions>
 <Grid.RowDefinitions>
  <RowDefinition Height="1*"/>
  <RowDefinition Height="5*" MinHeight="200"/>
  <RowDefinition Height="1*"/>
 </Grid.RowDefinitions>
 <Image x:Name="img" Stretch="Uniform" Source="Orz.png" Grid.Column="1"
   Grid.Row="1">
   <Image.Clip>
    <RectangleGeometry Rect="0,0,200,200" x:Name="clipArea"/>
   </Image.Clip>

  </Image>
 <Image x:Name="img_grid_bg" Stretch="Uniform" Opacity="0.001"
   Source="Orz.png" Grid.Column="1" Grid.Row="1"
   MouseLeftButtonDown="onDown" MouseMove="onMove" />
 </Grid>
</Grid>

接著在 .cs檔中加入EventHandler內容:

//全域--用於記錄滑鼠左鍵是否在圖片上被按下
bool mouseClickDown = false;

滑鼠左鍵在圖片上按下時:

private void onDown(object sender, MouseButtonEventArgs e)
{
 mouseClickDown = true;
 Point pos = e.GetPosition(img);
 clipArea.Rect = new Rect(0, 0, pos.X, pos.Y);
}

滑鼠在圖片上移動時:

private void onMove(object sender, MouseEventArgs e)
{
 if (!mouseClickDown) return;
 Point pos = e.GetPosition(img);
 clipArea.Rect = new Rect(0, 0, pos.X, pos.Y);
}

當滑鼠離開、滑鼠左鍵放開時:

private void onLeave(object sender, MouseEventArgs e)
{
 mouseClickDown = false;
}
private void onRectUp(object sender, MouseButtonEventArgs e)
{
 mouseClickDown = false;
}


1.其中對Image.clip元件給定一個名字(在此即clipArea),再從程式內部來對它指定新的Clip範圍,至於想要取多少的U、V,再依個人需求去做計算。
2.在.xmal中,給了兩個Image元件,其中一個主要用來觸發滑鼠事件,而另一個負責顯示U、V的效果,而U、V的範圍主要對「clipArea」指定數值來決定。

沒有留言:

張貼留言