解决SilverLight的图片裁剪问题

WPF有CroppedBitmap类,能够很方便的裁剪图片,可是SilverLight里面没有。这可麻烦了用SilverLight做游戏的同仁们。

虽然可以用一个Border包着一个Image来解决,但程序员往往喜欢用更简单的方法。

 

这里给出一个用转换器实现的裁剪案例

代码只保证SilverLight 4.0测试通过,其他版本未测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public class CroppedBitmapConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        BitmapImage bi = value as BitmapImage;
        if (bi == null) return null;
 
        Rect rect;
        if (parameter is Rect)
        {
            rect = (Rect)parameter;
        }
        else
        {
            try
            {
                string[] s = parameter.ToString().Split(',');
                rect = new Rect(double.Parse(s[0]), double.Parse(s[1]), double.Parse(s[2]), double.Parse(s[3]));
            }
            catch
            {
                rect = new Rect(0, 0, bi.PixelWidth, bi.PixelHeight);
            }
        }
 
        Image image = new Image();
        image.Stretch = Stretch.None;
        image.RenderTransform = new TranslateTransform { X = -rect.X, Y = -rect.Y };
        image.Source = bi;
 
        Canvas canvas = new Canvas();
        canvas.Width = rect.Width;
        canvas.Height = rect.Height;
        canvas.Children.Add(image);
 
        return new WriteableBitmap(canvas, null);
    }
 
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

相应的前台代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<UserControl
    xmlns:local="clr-namespace:SilverlightApplication1"
    x:Class="SilverlightApplication1.MainPage"
    Width="640" Height="480">
 
    <UserControl.Resources>
        <local:CroppedBitmapConverter x:Key="CroppedBitmapConverter"/>
    </UserControl.Resources>
 
    <Grid x:Name="LayoutRoot" Background="#FF959595">
        <Image x:Name="image" Source="未命名.jpg" VerticalAlignment="Top" HorizontalAlignment="Left" Stretch="None" />
        <Image DataContext="{Binding Source, ElementName=image}"
               Source="{Binding ConverterParameter=180\,0\,130\,100, Converter={StaticResource CroppedBitmapConverter}, Mode=OneWay}"
               VerticalAlignment="Bottom" HorizontalAlignment="Left" Stretch="None" />
    </Grid>
</UserControl>

最终的效果

posted @   Aimeast  阅读(2602)  评论(1编辑  收藏  举报
点击右上角即可分享
微信分享提示