Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Create ImageBrush in C# code

Tags:

c#

wpf

In XAML:

    <Rectangle Stroke="Aqua" Opacity="0.7" StrokeThickness="10" Canvas.Left="24" Canvas.Top="22" Height="86" Width="102">
        <Rectangle.Fill>
            <ImageBrush ImageSource="C:\Users\xiaorui.dong\Pictures\profile.jpeg"></ImageBrush>
        </Rectangle.Fill>
    </Rectangle>

XAML works fine, but how to create the above ImageBrush in C# code:

C# should be like this:

Rectangle rectangle = new Rectangle();
rectangle.StrokeThickness = 10;
rectangle.Height = 200;
rectangle.Width = 100;
rectangle.SetValue(Canvas.LeftProperty, 100d);
rectangle.SetValue(Canvas.TopProperty, 100d);
rectangle.Fill = new ImageBrush(new BitmapImage(new Uri(@"C:\Users\xiaorui.dong\Pictures\profile.jpeg")));
like image 791
dongx Avatar asked Nov 23 '12 20:11

dongx


2 Answers

I'm guessing the problem is with locating the image and that the exception you're getting is because you don't provide the UriKind parameter. Try giving UriKind.Relative as a parameter to the Uri:

rectangle.Fill = new ImageBrush(new BitmapImage(
    new Uri(@"C:\Users\xiaorui.dong\Pictures\profile.jpeg", UriKind.Relative)));
like image 130
Adi Lester Avatar answered Nov 07 '22 05:11

Adi Lester


In c# you can use it like , first thing is remove the fill from XAML then use the same code in c# as you have used it . It must work.

ImageBrush ib = new ImageBrush();

ib.ImageSource = new BitmapImage(new Uri("your path",UriKind.Relative));
rectangle.Fill = ib;
like image 8
SinhaOjas Avatar answered Nov 07 '22 05:11

SinhaOjas