I'm dynamically generating image from text, and existing image on my asp.net website.
Here is the code:
protected void Button1_Click(object sender, EventArgs e)
{
var tytul = Request.QueryString["Tytul"];
var tresc = Request.QueryString["Tresc"];
var font = new Font("Verdana", 23);
var brushForeColor = new SolidBrush(Color.Black);
var brushBackColor = new SolidBrush(Color.FromArgb(248, 247, 182));
var test = new Bitmap(450, 60);
var graphicstest = Graphics.FromImage(test);
var width = (int)graphicstest.MeasureString(tresc, font).Width;
var height = (int)graphicstest.MeasureString(tresc, font).Height;
while (width > 450)
{
height = height + 25;
width = width - 450;
}
var heightall = height + 40 + 30 + 100;
var bitmap = new Bitmap(450, heightall);
var graphics = Graphics.FromImage(bitmap);
var displayRectangle = new Rectangle(new Point(0, 0), new Size(450, 40));
graphics.FillRectangle(brushBackColor, displayRectangle);
//Define string format
var format1 = new StringFormat(StringFormatFlags.NoClip);
format1.Alignment = StringAlignment.Center;
var format2 = new StringFormat(format1);
//Draw text string using the text format
graphics.DrawString(tytul, font, brushForeColor, displayRectangle, format2);
// Rysowanie drugiego boxa
brushBackColor = new SolidBrush(Color.FromArgb(253, 253, 202));
font = new Font("Verdana", 18);
displayRectangle = new Rectangle(new Point(0, 40), new Size(450, height + 30));
graphics.FillRectangle(brushBackColor, displayRectangle);
displayRectangle = new Rectangle(new Point(0, 55), new Size(450, height + 15));
graphics.DrawString(tresc, font, brushForeColor, displayRectangle, format2);
graphics.DrawImage(System.Drawing.Image.FromFile(Server.MapPath(".") + "/gfx/layout/podpis.png"), new Point(0, height + 70));
Response.ContentType = "image/png";
bitmap.Save(Response.OutputStream, ImageFormat.Png);
}
As you can see the bitmap is saved and showed on aspx page after postback. What I wanna do is when user click Button1, then image is generated and browser download window pops up, without saving on server or showing on page. How to do this? Please help me.
Cheers.
You need to add a Content-Disposition header.
After you save the file:
Response.AppendHeader("content-disposition", "attachment; filename=podpis.png" );
Response.WriteFile("yourfilepath/podpis.png");
Response.End;
Related
I'm trying to print some text data using an event handler, and then print a PDF on the second page.
I'm using pdfium viwer to do this and it works individually. But I'm struggling to combine them.
I need to get the two to print as 2 pages of the same print document, as I want to use a duplex printer to print the pdf on the back. I don't just want to send two individual pages.
Sample code:
To Print PDF:
private void button1_Click(object sender, EventArgs e)
{
string filena = #textBox1.Text;
PrintPDF("M2020", "A4", filena, 1);
}
public bool PrintPDF(string printer, string paperName, string filename, int copies)
{
try
{
// Create the printer settings for our printer
var printerSettings = new PrinterSettings
{
PrinterName = printer,
Copies = (short)copies,
};
// Create our page settings for the paper size selected
var pageSettings = new PageSettings(printerSettings)
{
Margins = new Margins(0, 0, 0, 0),
};
foreach (PaperSize paperSize in printerSettings.PaperSizes)
{
if (paperSize.PaperName == paperName)
{
pageSettings.PaperSize = paperSize;
break;
}
}
// Now print the PDF document
using (var document = PdfDocument.Load(filename))
{
using (var printDocument = document.CreatePrintDocument())
{
printDocument.PrinterSettings = printerSettings;
printDocument.DefaultPageSettings = pageSettings;
printDocument.PrintController = new StandardPrintController();
printDocument.Print();
}
}
return true;
}
catch
{
return false;
}
}
And my original code to print a QR code:
private void Doc_PrintPage(object sender, PrintPageEventArgs e)
{
string s2 = "Modified by: ";
string s6 = "Author: " + author;
string s4 = "Created: " + drawdate;
QRCodeGenerator qrGenerator1 = new QRCodeGenerator();
QRCodeData qrCodeDataPrint = qrGenerator1.CreateQrCode(qrcodedata, QRCodeGenerator.ECCLevel.Q, false, false);
Bitmap qrCodeImagePrint = (new QRCode(qrCodeDataPrint)).GetGraphic(20);
Bitmap bmimg = new Bitmap(this.pictureBox2.Width, this.pictureBox2.Height);
this.pictureBox2.DrawToBitmap(bmimg, new Rectangle(0, 0, this.pictureBox2.Width, this.pictureBox2.Height));
System.Drawing.Font f1 = new System.Drawing.Font("Arial", 5f, FontStyle.Bold, GraphicsUnit.Millimeter);
System.Drawing.Font f2 = new System.Drawing.Font("Arial", 2f, GraphicsUnit.Millimeter);
System.Drawing.Font f3 = new System.Drawing.Font("Arial", 3f, GraphicsUnit.Millimeter);
System.Drawing.Font barc = new System.Drawing.Font("Code39Azalea", 36f, GraphicsUnit.Point);
e.Graphics.PageUnit = GraphicsUnit.Millimeter;
Pen blackPen = new Pen(Color.Black, 1f);
Rectangle rect = new Rectangle(165, 35, 30, 30);
Rectangle qrcodetest = new Rectangle(170, 40, 25, 25);
Rectangle btmimg = new Rectangle(60, 140, 120, 120);
Rectangle combox = new Rectangle(20, 145, 160, 40);
e.Graphics.DrawImage(qrCodeImagePrint, qrcodetest);
e.Graphics.DrawRectangle(blackPen, qrcodetest);
e.Graphics.DrawString(this.procreq, f1, Brushes.Black, new Point(50, 5));
e.Graphics.DrawString(s1, f1, Brushes.Black, new Point(150, 70));
e.Graphics.DrawString(s1z, f2, Brushes.Black, new Point(150, 75));
e.Graphics.DrawString(qrissuedby, f2, Brushes.Black, new Point(20, 264));
e.Graphics.DrawString(s6, f2, Brushes.Black, new Point(20, 267));
e.Graphics.DrawString(s4, f2, Brushes.Black, new Point(20, 270));
e.Graphics.DrawString(s2, f2, Brushes.Black, new Point(20, 273));
e.Graphics.DrawString(s3, f2, Brushes.Black, new Point(20, 276));
e.Graphics.DrawString(s5, f2, Brushes.Black, new Point(20, 279));
e.Graphics.DrawString(this.notebox.Text, f3, Brushes.Black, combox);
e.Graphics.DrawImage(bitmap1, btmimg);
bmimg.Dispose();
bitmap1.Dispose();
}
Any help would be much appreciated!
Thanks
Andrew
Ok, think i was going about that in completely the wrong way. What I eventually did was use the pdfium viewer to render the pdf as a bitmap, and then printed that as the second page.
e.Graphics.PageUnit = GraphicsUnit.Millimeter;
Pen blackPen = new Pen(Color.Black, 1f);
int actualwidth = (int)(e.Graphics.DpiX * 210 / 25.4f);
int actualHeight = (int)(e.Graphics.DpiY * 297 / 25.4f);
using (var pdfDocument = PdfiumViewer.PdfDocument.Load(#textBox1.Text))
{
var bitmapImage = pdfDocument.Render(0, actualwidth, actualHeight, false);
pictureBox1.Image = bitmapImage;
pictureBox1.Image.RotateFlip((RotateFlipType.Rotate90FlipNone));
}
if (pgnum == 1)
{
Debug.WriteLine("firing first page " + pgnum);
Rectangle qrcodetest = new Rectangle(170, 40, 25, 25);
e.Graphics.DrawRectangle(blackPen, qrcodetest);
e.HasMorePages = true;
pgnum++;
Debug.WriteLine(pgnum);
}
else
{
Debug.WriteLine("firing second page " + pgnum);
GraphicsUnit units = GraphicsUnit.Millimeter;
Rectangle srcRect = new Rectangle(0, 0, 199, 281);
//e.Graphics.Q
e.Graphics.Clear(Color.White);
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
e.Graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
e.Graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
e.Graphics.DrawImage(pictureBox1.Image, srcRect);
e.HasMorePages = false;
}
This does work.... but the printed version of the PDF is very poor quality. I've tried using interpolation etc.... but doesn't seem to make any difference, so not sure i'm putting it in the right place?
Also, i've tried using the bitmap variable rather than the picturebox image, but it seems to generate the same result. The PDF prints much better.
Thanks
Andrew
Hi I am using below code and the bar code is generating well but how can I remove text written down to label.
public void generateBarcode(string id)
{
int w = id.Length * 55;
Bitmap oBitmap = new Bitmap(w, 100);
Graphics oGraphics = Graphics.FromImage(oBitmap);
Font oFont = new Font("IDAutomationHC39M", 18);
PointF oPoint = new PointF(2f, 2f);
SolidBrush oBrushWrite = new SolidBrush(Color.Black);
SolidBrush oBrush = new SolidBrush(Color.White);
oGraphics.FillRectangle(oBrush, 0, 0, w, 100);
oGraphics.DrawString("*" + id + "*", oFont, oBrushWrite, oPoint);
System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
using (System.IO.FileStream fs = System.IO.File.Open(Server.MapPath("~/img/barcodes/") + id + ".jpg", FileMode.Create))
{
oBitmap.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg);
}
oBitmap.Dispose();
imgbarcode.ImageUrl = "~/img/barcodes/" + id + ".jpg";
}
My bar code is generating as below. Here I need to remove the bar code text as 76
According to this, the font you need to use without text is "IDAutomationC39M". Unfortunately, that's not in the free version.
I'm using a FlowDocument to create a report. Now, I created a paginator in order to be able to repeat the header on every page, however, it does not get rendered on each page. I suspect the problem is that the Viewbox is not rendered/created untill you try to display it.
This is my GetPage method:
public override DocumentPage GetPage(int pageNumber) {
DocumentPage page = m_Paginator.GetPage(pageNumber);
ContainerVisual newpage = new ContainerVisual();
DrawingVisual title = new DrawingVisual();
using (DrawingContext ctx = title.RenderOpen())
{
var header = getHeader();
RenderTargetBitmap bmp = new RenderTargetBitmap(165, 32, 96, 96,
PixelFormats.Pbgra32);
bmp.Render(header);
ctx.DrawImage(bmp,new Rect(new Point(0,0),new Size(166, 33)));
}
ContainerVisual smallerPage = new ContainerVisual();
title.Children.Add(getHeader());
newpage.Children.Add(title);
smallerPage.Children.Add(page.Visual);
smallerPage.Transform = new MatrixTransform(0.95, 0, 0, 0.95, 0.025 * page.ContentBox.Width, 0.025 * page.ContentBox.Height);
newpage.Children.Add(smallerPage);
newpage.Transform = new TranslateTransform(m_Margin.Width, m_Margin.Height);
return new DocumentPage(newpage, m_PageSize, Move(page.BleedBox), Move(page.ContentBox));
}
Here's the Move method:
Rect Move(Rect rect) {
if (rect.IsEmpty) {
return rect;
}
else {
return new Rect(rect.Left + m_Margin.Width, rect.Top + m_Margin.Height,
rect.Width, rect.Height);
}
}
And here is getHeader() (Yes, I know, it should be GetHeader() - them conventions)
private Viewbox getHeader() {
Grid gr = new Grid();
var sr = Application.GetResourceStream(new Uri("Propuestas;component/img/log.xaml", UriKind.Relative));
var img = (Canvas)XamlReader.Load(new XmlTextReader(sr.Stream));
var logo = new Viewbox {
Child = img,
HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Center,
Width = 165
};
var detalles = new TextBlock {
FontSize = 10,
FontFamily = new FontFamily("Verdana"),
Padding = new Thickness(logo.Width + 15, 0, 0, 0)
};
App.Comando.CommandText = "SELECT RazEmp, DirEmp, CpEmp, PobEmp, ProEmp, TelEmp, CifEmp FROM META4.Empresa";
using (var reader = App.Comando.ExecuteReader())
while (reader.Read())
detalles.Text = "" + reader.GetString(0).Trim() + "\n" + reader.GetString(1).Trim() + "\n" +
reader.GetDecimal(2) + " - " + reader.GetString(3).Trim() + "(" +
reader.GetString(4).Trim() + ")\n" + "Tlf: " + reader.GetString(5).Trim() +
"\nCIF: " + reader.GetString(6).Trim();
var pd = new TextBox {
Text = "PEDIDO DE COMPRA",
TextAlignment = TextAlignment.Left,
FontSize = 19,
FontFamily = new FontFamily("Verdana"),
FontWeight = FontWeights.Bold,
Background = new SolidColorBrush(Color.FromRgb(192, 192, 192)),
Margin = new Thickness(logo.Width + 15, 10, 0, 20),
BorderThickness = new Thickness(0)
};
gr.ColumnDefinitions.Add(new ColumnDefinition());
gr.ColumnDefinitions.Add(new ColumnDefinition());
gr.RowDefinitions.Add(new RowDefinition());
gr.RowDefinitions.Add(new RowDefinition());
Grid.SetRow(logo, 0);
Grid.SetRow(detalles, 0);
Grid.SetRow(pd, 1);
Grid.SetColumn(pd, 0);
Grid.SetColumnSpan(pd, 2);
Grid.SetColumnSpan(detalles, 2);
gr.Children.Add(logo);
gr.Children.Add(detalles);
gr.Children.Add(pd);
Viewbox vb = new Viewbox();
vb.Child = gr;
return vb;
}
However, when I hit print, it prints it normally, without repeating the header. I can see the query running up in debug, so addHeader() gets executed. The width and height are predetermined and fixed. Both header.Width/header.Height and header.ActualWidth/header.ActualHeight give me either 0 or NaN, which makes me believe that the viewbox isn't rendered in the background. Is there any way I would be able to repeat this on each page?
The problem is that my header contains one image and two parts text. I already had it created to be put on the first page only, but now the requirements have changed and I have to repeat it on every page.
Any help is greatly appreciated.
Later Edit: Also tried this, didn't work either.
private static BitmapSource CaptureScreen(Visual target, double dpiX, double dpiY) {
if (target == null)
return null;
Size size = new Size(165, 31.536);
RenderTargetBitmap rtb = new RenderTargetBitmap((int)(size.Width * dpiX / 96.0),
(int)(size.Height * dpiY / 96.0),
dpiX,
dpiY,
PixelFormats.Pbgra32);
DrawingVisual dv = new DrawingVisual();
using (DrawingContext ctx = dv.RenderOpen()) {
VisualBrush vb = new VisualBrush(target);
ctx.DrawRectangle(vb, null, new Rect(new Point(), size));
}
rtb.Render(dv);
return rtb;
}
Fixed by adding
vb.Measure(new System.Windows.Size(headerWidth, headerHeight));
vb.Arrange(new Rect(15,15,headerWidth,headerHeight));
vb.UpdateLayout();
to the getHeader method. Now it looks like this:
private Viewbox getHeader() {
Grid gr = new Grid();
var sr = Application.GetResourceStream(new Uri("Propuestas;component/img/log.xaml", UriKind.Relative));
var img = (Canvas)XamlReader.Load(new XmlTextReader(sr.Stream));
var logo = new Viewbox {
Child = img,
HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Center,
Width = 165
};
var detalles = new TextBlock {
FontSize = 10,
FontFamily = new FontFamily("Verdana"),
Padding = new Thickness(logo.Width + 15, 0, 0, 0)
};
App.Comando.CommandText = "SELECT RazEmp, DirEmp, CpEmp, PobEmp, ProEmp, TelEmp, CifEmp FROM META4.Empresa";
using (var reader = App.Comando.ExecuteReader())
while (reader.Read())
detalles.Text = "" + reader.GetString(0).Trim() + "\n" + reader.GetString(1).Trim() + "\n" +
reader.GetDecimal(2) + " - " + reader.GetString(3).Trim() + "(" +
reader.GetString(4).Trim() + ")\n" + "Tlf: " + reader.GetString(5).Trim() +
"\nCIF: " + reader.GetString(6).Trim();
var pd = new TextBox {
Text = "PEDIDO DE COMPRA " + numPCO,
TextAlignment = TextAlignment.Left,
FontSize = 19,
FontFamily = new FontFamily("Verdana"),
FontWeight = FontWeights.Bold,
Background = new SolidColorBrush(Color.FromRgb(192, 192, 192)),
Margin = new Thickness(logo.Width + 15, 10, 0, 20),
BorderThickness = new Thickness(0)
};
gr.ColumnDefinitions.Add(new ColumnDefinition());
gr.ColumnDefinitions.Add(new ColumnDefinition());
gr.RowDefinitions.Add(new RowDefinition());
gr.RowDefinitions.Add(new RowDefinition());
Grid.SetRow(logo, 0);
Grid.SetRow(detalles, 0);
Grid.SetRow(pd, 1);
Grid.SetColumn(pd, 0);
Grid.SetColumnSpan(pd, 2);
Grid.SetColumnSpan(detalles, 2);
gr.Children.Add(logo);
gr.Children.Add(detalles);
gr.Children.Add(pd);
Viewbox vb = new Viewbox();
vb.Child = gr;
vb.Measure(new System.Windows.Size(headerWidth, headerHeight));
vb.Arrange(new Rect(15,15,headerWidth,headerHeight));
vb.UpdateLayout();
return vb;
}
I am creating a PNG picture, using the Bitmap object, using Drawing.Graphics . I create a Bitmap, insert a background image and draw some strings.
Now, when I save the image on the disk, the files does not have my strings!
I am doing this in ASP.NET MVC, where this is my controllers signature:
[AcceptVerbs(HttpVerbs.Get)]
public string GetNewsletterPicture(string headline, string tagline)
When I don't save the image on the disk and instead returns a FileStreamResult from a MemoryStream, the image looks perfectly.
So there is some problem that when I save the image to the disk, the strings are "forgotten" somehow.
Any ideas?
My code:
ColorConverter converter = new ColorConverter();
Color textColor = (Color)converter.ConvertFromString("#FF58595B");
int width = 598;
int height = 77;
int offSet = 40;
int shadowOffset = 1;
var bmp = new Bitmap(width, height);
using (Graphics g = Graphics.FromImage(bmp))
{
g.Clear(Color.LightGray);
Image backgroundImg = new Bitmap(Server.MapPath("~/Static/Images/bgimg.png"));
g.DrawImage(backgroundImg,0,0);
StringFormat sf= new StringFormat();
sf.Alignment = StringAlignment.Center;
var rectangleTop = new RectangleF(0, 0, width, height);
var rectangleTopShadowHack = new RectangleF(shadowOffset, shadowOffset, width + shadowOffset, height + shadowOffset);
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
// only show headline and center it
if (!string.IsNullOrEmpty(tagline))
{
var rectangleBottomShadowHack = new RectangleF(shadowOffset, offSet + shadowOffset, width + shadowOffset, height - offSet + shadowOffset);
var rectangleBottom = new RectangleF(0, offSet, width, height - offSet);
g.DrawString(tagline, new Font("Verdana", 18), new SolidBrush(Color.White), rectangleBottomShadowHack, sf);
g.DrawString(tagline, new Font("Verdana", 18), new SolidBrush(textColor), rectangleBottom, sf);
}
else
{
sf.LineAlignment = StringAlignment.Center;
}
g.DrawString(headline, GetFont("Sentinel-Bold", 28, FontStyle.Bold), new SolidBrush(Color.White), rectangleTopShadowHack, sf);
g.DrawString(headline, GetFont("Sentinel-Bold", 28, FontStyle.Bold), new SolidBrush(textColor), rectangleTop, sf);
g.Save();
var fileName = Guid.NewGuid().ToString() + ".png";
var path = Server.MapPath("~/Static/Previews/" + fileName);
bmp.Save(path, ImageFormat.Png);
return fileName;
If in doubt, it is the g.DrawString which is not being saved on the picture.
NEW atttempt (still not working):
[AcceptVerbs(HttpVerbs.Get)]
public string GetNewsletterPicture(string headline, string tagline)
{
ColorConverter converter = new ColorConverter();
Color textColor = (Color)converter.ConvertFromString("#FF58595B");
int width = 598;
int height = 77;
int offSet = 40;
int shadowOffset = 1;
var bmp = new Bitmap(width, height);
using (Graphics g = Graphics.FromImage(bmp))
{
g.Clear(Color.LightGray);
Image backgroundImg = new Bitmap(Server.MapPath("~/Static/Images/bgimg.png"));
g.DrawImage(backgroundImg,0,0);
StringFormat sf= new StringFormat();
sf.Alignment = StringAlignment.Center;
var rectangleTop = new RectangleF(0, 0, width, height);
var rectangleTopShadowHack = new RectangleF(shadowOffset, shadowOffset, width + shadowOffset, height + shadowOffset);
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
// only show headline and center it
if (!string.IsNullOrEmpty(tagline))
{
var rectangleBottomShadowHack = new RectangleF(shadowOffset, offSet + shadowOffset, width + shadowOffset, height - offSet + shadowOffset);
var rectangleBottom = new RectangleF(0, offSet, width, height - offSet);
g.DrawString(tagline, new Font("Verdana", 18), new SolidBrush(Color.White), rectangleBottomShadowHack, sf);
g.DrawString(tagline, new Font("Verdana", 18), new SolidBrush(textColor), rectangleBottom, sf);
}
else
{
sf.LineAlignment = StringAlignment.Center;
}
g.DrawString(headline, GetFont("Sentinel-Bold", 28, FontStyle.Bold), new SolidBrush(Color.White), rectangleTopShadowHack, sf);
g.DrawString(headline, GetFont("Sentinel-Bold", 28, FontStyle.Bold), new SolidBrush(textColor), rectangleTop, sf);
g.Flush(FlushIntention.Sync);
}
var fileName = Guid.NewGuid().ToString() + ".png";
var path = Server.MapPath("~/Static/Previews/" + fileName);
bmp.Save(path, ImageFormat.Png);
return fileName;
//MemoryStream stm = new MemoryStream();
//bmp.Save(stm,System.Drawing.Imaging.ImageFormat.Png);
//stm.Position = 0;
//return new FileStreamResult(stm, "image/png");
}
I can't tell for sure, but it looks like you might be confusing g.Save() with g.Flush().
You need to call g.Flush(FlushIntention.Sync) instead of g.Save(). You should probably also call bmp.Save() outside of the using block:
var bmp = new Bitmap(width, height);
using (Graphics g = Graphics.FromImage(bmp))
{
//...
g.Flush(FlushIntention.Sync);
}
var fileName = Guid.NewGuid().ToString() + ".png";
var path = Server.MapPath("~/Static/Previews/" + fileName);
bmp.Save(path, ImageFormat.Png)
Save() is used to save the current graphics state so that you can modify it and then restore it later.:
GraphicsState oldState = g.Save();
// Make some changes to the graphics state...
g.Restore(oldState);
Flush() on the other hand, is used to force the graphics object to complete any pending operations. By passing FlushIntention.Sync as a parameter, Flush() won't return until the flushing is complete.
I want to show a brush on my stackpanel in the following behavior:
Brush is an image 240x120
panel is 240x60
I want to show a part of the brush like rect(0, 30, 240, 60) (so that the image on the panel is moved down a bit)
tried it with viewport and Viewbox with no result (empty Panel)
This is my code:
for (int i = 0; i < listExplorationData.Count; i++)
{
StackPanel panelLoop = new StackPanel();
panelLoop.Name = "panel_" + i.ToString();
panelLoop.Width = 240;
panelLoop.Height = 60;
panelLoop.Margin = new Thickness(0, 60 * i, 0, 0);
BitmapImage image = new BitmapImage(
new Uri("pack://application:,,,/GW2-MyWorldExploration;component/Images/" +
listExplorationData[i].mapname_en.Replace(" ", "_") +
"_loading_screen.jpg"));
ImageBrush brush = new ImageBrush();
brush.ImageSource = image;
brush.Stretch = Stretch.None;
brush.Viewport = new Rect(0, 30, 240, 60);
panelLoop.Background = brush;
mainStackPanel.Children.Add(panelLoop);
}
In order to show part of the ImageBrush you would have to set the Viewbox. If you want to specify the viewbox in absolute units, you would also have to set the ViewboxUnits property:
brush.ViewboxUnits = BrushMappingMode.Absolute;
brush.Viewbox = new Rect(0, 30, 240, 60);