开发者

Clipping image using Path in Silverlight

How to clip image in Silverlight using custom Path (in code behind, not in XAML). I have puzzle piece like shape written in path and want to use it to clip any image.

Currently it works by clipping using rectangle, The code is (C#):

private void UserControl_Loaded(object sender, RoutedEventArgs e)
    {
        int NUM_COLUMN = 8;
        int NUM_ROW = 8;
        double 开发者_运维技巧gridWidth = 60;
        double gridHeight = 60;
        string url = "Images/Sun.png";

        // C#
        for (int i = 0; i < NUM_COLUMN; i++)
        {
            for (int j = 0; j < NUM_ROW; j++)
            {
                double offsetX = (double)i * gridWidth;
                double offsetY = (double)j * gridHeight;

                Image image = new Image();
                image.Source = new BitmapImage(new Uri(url, UriKind.Relative));

                // clip the image

                RectangleGeometry r = new RectangleGeometry();


                r.Rect = new Rect(offsetX, offsetY, gridWidth, gridHeight);
                image.Clip = r;                 

                this.ClipCanvas.Children.Add(image);
            }
        }
    }

There is only one Canvas in XAML called ClipCanvas.


Okay, not ideal. But works from the code-behind

Image image = XamlReader.Load(@"<Image xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"" xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"" Clip=""M 41.1,33.7 C 41.1,33.7 39.9,32.2 39.9,30.8 C 39.9,30.6 39.5,29.8 39.3,29.5 C 39.1,29.3 38.4,28.6 37.8,28.2 C 37.2,27.9 35,26.6 34.6,22.4 Z "" />") as Image;
image.Source = new BitmapImage(new Uri("Desert.jpg", UriKind.Relative));

Set up in the clip in Xaml, and create the Image using an XamlReader. Tried other approaches, and this was the only one that worked.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜