I would like to generate some images dynamicaly. For that, I intend to create a XAML View, populate it with Data (using DataBinding) and then generate an image from the rendering of that view (kind of a screenshot).
Is there a way to do this in Silverligth or WPF?
In WPF:
public static Image GetImage(Visual target)
{
if (target == null)
{
return null; // No visual - no image.
}
var bounds = VisualTreeHelper.GetDescendantBounds(target);
var bitmapHeight = 0;
var bitmapWidth = 0;
if (bounds != Rect.Empty)
{
bitmapHeight = (int)(Math.Floor(bounds.Height) + 1);
bitmapWidth = (int)(Math.Floor(bounds.Width) + 1);
}
const double dpi = 96.0;
var renderBitmap =
new RenderTargetBitmap(bitmapWidth, bitmapHeight, dpi, dpi, PixelFormats.Pbgra32);
var visual = new DrawingVisual();
using (var context = visual.RenderOpen())
{
var brush = new VisualBrush(target);
context.DrawRectangle(brush, null, new Rect(new Point(), bounds.Size));
}
renderBitmap.Render(visual);
return new Image
{
Source = renderBitmap,
Width = bitmapWidth,
Height = bitmapHeight
};
}
Use the WriteableBitmap and its Render function in Silverlight.
In WPF use this trick by using the RenderTargetBitmap and its Render function
You can add the controls (data after they are databound) that you want to capture to a ViewBox - http://www.wpftutorial.net/ViewBox.html
From there, you can create an image using WriteableBitmap - http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.writeablebitmap%28VS.95%29.aspx
Related
I encountered strange behaviour when loading image from byte array aquired from stream. Most images are correct, I would say 99% of them. But i saw so far two times something like this below. Image in the middle is shown like a set of random pixels, not the real image.
Image can be loaded correctly in other client application (sliverlight) but i can't show that.
In WPF client i have something like that:
Does someone had issue like this? Or any idea what might cause it? Maybe i should look on server side (image is show in other, older client and code to load that is known to me).
Code looks like that:
public async Task<ImageCreatePictureBox> CreatePictureBox(IBaseObj pmIBaseObj, IObj pmObj)
{
var lcContainer = new Grid
{
Width = pmObj.PresObj.Width,
Height = pmObj.PresObj.Height
};
var gridBorder = new Border();
CustomImg imageControl = null;
FrameworkElement lcFrameworkElement = lcContainer;
if (!(pmIBaseObj is ImageBaseObj lcImageBaseObj))
return new ImageCreatePictureBox(null, lcContainer, lcFrameworkElement, pmObj);
if (!lcImageBaseObj.CustomBitMap)
{
try
{
var bitmapImage = BitmapImageHelper.ByteArrayToBitmapSource(lcImageBaseObj.Image, lcImageBaseObj.ImageWidth, lcImageBaseObj.ImageHeight);
imageControl = new CustomImg(pmIBaseObj.Width, pmIBaseObj.Height, pmObj)
{
Source = bitmapImage,
Height = lcImageBaseObj.Height,
Width = lcImageBaseObj.Width
};
}
catch (Exception e)
{
var src = new BitmapImage(new Uri(Helper.GetPathToImage("dummy")));
imageControl = new CustomImg(pmIBaseObj.Width, pmIBaseObj.Height, pmObj)
{
Source = src,
Height = lcImageBaseObj.Height,
Width = lcImageBaseObj.Width
};
Helper.WriteToDebug(e);
}
}
else
{
try
{
var bitmapImage = BitmapImageHelper.ByteArrayToBitmapSource(lcImageBaseObj.Image, lcImageBaseObj.ImageWidth, lcImageBaseObj.ImageHeight);
imageControl = new CustomImg(pmIBaseObj.Width, pmIBaseObj.Height, pmObj)
{
Source = bitmapImage,
Height = lcImageBaseObj.Height,
Width = lcImageBaseObj.Width
};
}
catch (Exception e)
{
if (imageControl == null)
imageControl = new CustomImg(pmIBaseObj.Width, pmIBaseObj.Height, pmObj);
var src = new BitmapImage(new Uri(Helper.GetPathToImage("dummy")));
imageControl = new CustomImg(pmIBaseObj.Width, pmIBaseObj.Height, pmObj)
{
Source = src,
Height = lcImageBaseObj.Height,
Width = lcImageBaseObj.Width
};
Helper.WriteToDebug(e);
}
}
(...)
return new ImageCreatePictureBox(imageControl, lcContainer, lcFrameworkElement, pmObj);
}
public static BitmapSource ByteArrayToBitmapSource(Byte[] BArray, int imgWidth, int imgHeight)
{
try
{
var width = imgWidth;
var height = imgHeight;
var dpiX = 90d;
var dpiY = 90d;
var pixelFormat = PixelFormats.Pbgra32;
var bytesPerPixel = (pixelFormat.BitsPerPixel + 7) / 8;
var stride = bytesPerPixel * width;
var bitmap = BitmapSource.Create(width, height, dpiX, dpiY, pixelFormat, null, BArray, stride);
return bitmap;
}
catch (Exception e)
{
return BytesToBitmapImage(BArray);
}
}
i have a little problem. I want to export to an image my charts. I known that is possible with the code given by beto-rodriguez (here).
But i have a problem, i can't have what i could have by displaying it in the screen. See the image above. On the bottom right, i have the image saved in png. And in the left of the image, i have the chart with all the parameters displayed where i want.
Do you known if it's possible to have the same chart (in the left) in the saved image ?
Actually, i use a thread to capture (copy/paste) the image automatically.
Do you known what are the parameters i must set on to have the correct image ?
Double chart
Thanks in advance.
Regards.
********************************* After edit
Sorry for my late repsonse. I try what you said but unfornately I can't made that i want.
I will explain what i do:
I have a class "MakeReport" who can call another class "GraphMaker" with:
MyGraph = new GraphMaker();
MyGraph = GiveAGraph(MyGraph);
And the class "MakeReport" will complete the chart with some values with the sub-program "GiveAGraph()":
GraphData.SeriesCollection.Add(new RowSeries
{
Title = Criteria,
Values = DataValues,
ScalesYAt = Index,
DataLabels = true
});
End of "GiveAGRaph()".
Now I have a chart ready to display, i want to use it to make an image and for test (and debug) i show it:
// Chart to Image
MyGraph.GiveMeAnImageFromChart(); <-- to make a picture with the chart
// Show the graph
MyGraph.Show(); <-- for debug and test, i display it.
With "MyGraph.GiveAnImageFromChart()", i don't have the same result than "MyGraph.Show()". The picture (save as png) is different to the displayed chart.
The sub-program "GiveAnImageFromChart" included in the "GraphMaker" class is :
public void GiveMeAnImageFromChart()
{
var viewbox = new Viewbox();
myChart.Background = Brushes.White;
myChart.DataContext = this;
// myChart il faut tout mettre en paramètres
viewbox.Child = myChart;
viewbox.Measure(myChart.RenderSize);
viewbox.Arrange(new Rect(new Point(0, 0), myChart.RenderSize));
myChart.Update(true, true); //force chart redraw
viewbox.UpdateLayout();
SaveToPng(myChart, "chart.png");
//png file was created at the root directory.
}
The "myChart" variable is public. The "SaveToPng" program used come from your example (here).
To save the picture, i try with the following method :
public System.Drawing.Bitmap ControlToImage(Visual target, double dpiX, double dpiY)
{
if (target == null)
{
return null;
}
// render control content
Rect bounds = VisualTreeHelper.GetDescendantBounds(target);
Console.WriteLine("Bounds width = " + bounds.Width + " et bounds height = " + bounds.Height);
RenderTargetBitmap rtb = new RenderTargetBitmap((int)(bounds.Width * dpiX / 96.0),
(int)(bounds.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 System.Windows.Point(), bounds.Size));
}
rtb.Render(dv);
//convert image format
MemoryStream stream = new MemoryStream();
BitmapEncoder encoder = new BmpBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(rtb));
encoder.Save(stream);
return new System.Drawing.Bitmap(stream);
}
With :
Bitmap ImageChart = MyGraph.ControlToImage(MyGraph, MyGraph.Width, MyGraph.Height);
With this method, i have an error because the "bounds.Width" and "bounds.Height" are equal to -8. And finally, i don't have any chart to convert.
I think i give a wrong "visual Target" in the "ControlImage" and I miss something but i don't know what. If you need more information, ask me.
Thanks in advance for your help.
PS: sorry for my english. Don't hesitate to correct me.
thanks to bto-rdz, i made a solution. I found that i didn't use Livecharts correctly.
So i post my code if someone need it.
This is my GraphMaker.xaml file:
<UserControl x:Class="MyProject.GraphMaker"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:MyProject"
mc:Ignorable="d"
d:DesignHeight="730" d:DesignWidth="1660">
<Grid>
</Grid>
</UserControl>
And my GraphMaker.xaml.cs file
using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using LiveCharts;
using LiveCharts.Wpf;
using System.Collections.Generic;
using System.ComponentModel;
namespace MyProject
{
public partial class GraphMaker : UserControl
{
// PUBLIC
public CartesianChart MyTestChart;
public SeriesCollection MySeriesCollection { get; set; }
public string[] Labels { get; set; }
public string AxisTitle { get; set; }
public Func<double, string> YFormatter { get; set; }
public Axis Axis1, Axis2, Axis3, Axis4, Axis5, Axis6, Axis7, Axis8, Axis9, Axis10, AxisXChart;
public GraphMaker()
{
InitializeComponent();
MySeriesCollection = new SeriesCollection();
MyTestChart = new CartesianChart
{
DisableAnimations = true,
Width = 1600,
Height = 700,
Series = MySeriesCollection
};
MyTestChart.LegendLocation = LegendLocation.Right;
// *** Axis 1 ***
Axis1 = new Axis();
Axis1.Foreground = Brushes.DodgerBlue;
Axis1.Position = AxisPosition.RightTop;
YFormatter = value => value.ToString("N2");
Axis1.LabelFormatter = YFormatter;
MyTestChart.AxisY.Add(Axis1);
// *** Axis 2 ***
Axis2 = new Axis();
Axis2.Foreground = Brushes.IndianRed;
Axis2.Position = AxisPosition.RightTop;
YFormatter = value => value.ToString("N2");
Axis2.LabelFormatter = YFormatter;
//MyTestChart.AxisY.Add(Axis2);
// *** Axis 3 ***
Axis3 = new Axis();
Axis3.Foreground = Brushes.Gold;
Axis3.Position = AxisPosition.RightTop;
YFormatter = value => value.ToString("N2");
Axis3.LabelFormatter = YFormatter;
//MyTestChart.AxisY.Add(Axis3);
// *** Axis 4 ***
Axis4 = new Axis();
Axis4.Foreground = Brushes.Gray;
Axis4.Position = AxisPosition.RightTop;
YFormatter = value => value.ToString("N2");
Axis4.LabelFormatter = YFormatter;
//MyTestChart.AxisY.Add(Axis4);
// *** Axis 5 ***
Axis5 = new Axis();
Axis5.Foreground = Brushes.DeepSkyBlue;
Axis5.Position = AxisPosition.RightTop;
YFormatter = value => value.ToString("N2");
Axis5.LabelFormatter = YFormatter;
//MyTestChart.AxisY.Add(Axis5);
// *** Axis 6 ***
Axis6 = new Axis();
Axis6.Foreground = Brushes.HotPink;
Axis6.Position = AxisPosition.RightTop;
YFormatter = value => value.ToString("N2");
Axis6.LabelFormatter = YFormatter;
//MyTestChart.AxisY.Add(Axis6);
// *** Axis 7 ***
Axis7 = new Axis();
Axis7.Foreground = Brushes.Orange;
Axis7.Position = AxisPosition.RightTop;
YFormatter = value => value.ToString("N2");
Axis7.LabelFormatter = YFormatter;
//MyTestChart.AxisY.Add(Axis7);
// *** Axis 8 ***
Axis8 = new Axis();
Axis8.Foreground = Brushes.RoyalBlue;
Axis8.Position = AxisPosition.RightTop;
YFormatter = value => value.ToString("N2");
Axis8.LabelFormatter = YFormatter;
//MyTestChart.AxisY.Add(Axis8);
// *** Axis 9 ***
Axis9 = new Axis();
Axis9.Foreground = Brushes.Black;
Axis9.Position = AxisPosition.RightTop;
Axis9.LabelFormatter = YFormatter;
//MyTestChart.AxisY.Add(Axis9);
// *** Axis 10 ***
Axis10 = new Axis();
Axis10.Foreground = Brushes.DarkTurquoise;
Axis10.Position = AxisPosition.RightTop;
YFormatter = value => value.ToString("N2");
Axis10.LabelFormatter = YFormatter;
//MyTestChart.AxisY.Add(Axis10);
AxisXChart = new Axis();
AxisXChart.Title = AxisTitle;
AxisXChart.Labels = Labels;
}
public void TakeTheChart()
{
var viewbox = new Viewbox();
viewbox.Child = MyTestChart;
viewbox.Measure(MyTestChart.RenderSize);
viewbox.Arrange(new Rect(new Point(0, 0), MyTestChart.RenderSize));
MyTestChart.Update(true, true); //force chart redraw
viewbox.UpdateLayout();
SaveToPng(MyTestChart, "Chart.png");
//png file was created at the root directory.
}
public void SaveToPng(FrameworkElement visual, string fileName)
{
var encoder = new PngBitmapEncoder();
EncodeVisual(visual, fileName, encoder);
}
private static void EncodeVisual(FrameworkElement visual, string fileName, BitmapEncoder encoder)
{
var bitmap = new RenderTargetBitmap((int)visual.ActualWidth, (int)visual.ActualHeight, 96, 96, PixelFormats.Pbgra32);
bitmap.Render(visual);
var frame = BitmapFrame.Create(bitmap);
encoder.Frames.Add(frame);
using (var stream = File.Create(fileName)) encoder.Save(stream);
}
}
}
Hope to help you.
Have a nice day. Bye.
The sample you pointed, is created a new chart instance in memory, that is why you are getting a different image, you could, reproduce the same properties in both charts, the one presented in the UI, and the one you are creating in memory, or you could just print the the current instance in the UI, as explained in this issue:
https://github.com/beto-rodriguez/Live-Charts/issues/243
Hope it helps
I have wrote extension method to save as image from cartesian chart for windows form. It can be edit your own way to get best one.
public static bool ChartToImage(this LiveCharts.WinForms.CartesianChart cartesianChart, LineSeries data, Axis AxisX, Axis AxisY,double Width, double Height, string fileName, string targetPath, out string locationOfImage, out Exception returnEx)
{
bool status = false;
returnEx = null;
locationPath = null;
try
{
var myChart = new LiveCharts.Wpf.CartesianChart
{
DisableAnimations = true,
Width = Width,
Height = Height,
Series = new SeriesCollection(cartesianChart.Series.Configuration)
{
new LineSeries
{
Title = data.Title,
LineSmoothness = data.LineSmoothness,
StrokeThickness = data.StrokeThickness,
PointGeometrySize = data.PointGeometrySize,
Stroke = data.Stroke,
Values=data.Values
}
}
};
myChart.AxisX.Add(new Axis { IsMerged = AxisX.IsMerged, FontSize = AxisX.FontSize, FontWeight = AxisX.FontWeight, Foreground = AxisX.Foreground, Separator = new LiveCharts.Wpf.Separator { Step = AxisX.Separator.Step, StrokeThickness = AxisX.Separator.StrokeThickness, StrokeDashArray = AxisX.Separator.StrokeDashArray, Stroke = AxisX.Separator.Stroke }, Title = AxisX.Title, MinValue = AxisX.MinValue, MaxValue = AxisX.MaxValue });
myChart.AxisY.Add(new Axis { IsMerged = AxisY.IsMerged, FontSize = AxisY.FontSize, FontWeight = AxisY.FontWeight, Foreground = AxisY.Foreground, Separator = new LiveCharts.Wpf.Separator { Step = AxisY.Separator.Step, StrokeThickness = AxisY.Separator.StrokeThickness, StrokeDashArray = AxisY.Separator.StrokeDashArray, Stroke = AxisX.Separator.Stroke }, Title = AxisY.Title, MinValue = AxisY.MinValue, MaxValue = AxisY.MaxValue });
var viewbox = new Viewbox();
viewbox.Child = myChart;
viewbox.Measure(myChart.RenderSize);
viewbox.Arrange(new Rect(new System.Windows.Point(0, 0), myChart.RenderSize));
myChart.Update(true, true); //force chart redraw
viewbox.UpdateLayout();
var encoder = new PngBitmapEncoder();
var bitmap = new RenderTargetBitmap((int)myChart.ActualWidth, (int)myChart.ActualHeight, 96, 96, PixelFormats.Pbgra32);
bitmap.Render(myChart);
var frame = BitmapFrame.Create(bitmap);
encoder.Frames.Add(frame);
string path = Path.Combine(targetPath, fileName);
using (var stream = File.Create(path))
{
encoder.Save(stream);
locationPath = path;
}
myChart = null;
viewbox = null;
encoder = null;
bitmap = null;
frame = null;
status = true;
}
catch (Exception ex)
{
returnEx = ex;
status = false;
}
return status;
}
On your main program :
if(cartesianChart1.ChartToImage(data,axisX,axisY,600,200,"test.png", locationImage, out string locationOfFile, out Exception returnEx))
{
System.Windows.Forms.MessageBox.Show(locationOfFile);
}
I have a simple wpf desktop application which prints a bitmap in landscape mode.
Under Windows 8/8.1 the printout is clipped on the bottom of the page while under Windows 7 it is printed correctly.
The code is really simple: load a bitmap, put it into an Image object, measure the printable area, arrange the image and print.
void printButton_Click(object sender, RoutedEventArgs e)
{
var pd = new PrintDialog();
if (!pd.ShowDialog().Value)
{
return;
}
pd.PrintTicket.PageOrientation = PageOrientation.Landscape;
pd.PrintTicket.PageBorderless = PageBorderless.None;
var printingCapabilities = pd.PrintQueue.GetPrintCapabilities(pd.PrintTicket);
var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.UriSource = new Uri("D:\\printTest.bmp");
bitmapImage.EndInit();
var imageuiElement = new Image { Source = bitmapImage };
var desiredSize = new Size(printingCapabilities.PageImageableArea.ExtentWidth, printingCapabilities.PageImageableArea.ExtentHeight);
imageuiElement.Measure(desiredSize);
imageuiElement.Arrange(new Rect(new Point(printingCapabilities.PageImageableArea.OriginWidth, printingCapabilities.PageImageableArea.OriginHeight), imageuiElement.DesiredSize));
pd.PrintVisual(imageuiElement, "MyImage");
}
The bitmap size is 1518 x 1092 pixels, 96 DPI, which is 40.2 x 28.9 cm.
I have found the question Cannot print a document with landscape orientation under Windows 8 (WPF, .NET 4.0)
but there is no good response for my issue (additionally I have no problem with printing as landscape itself).
I have tested it with different printers of different vendors, the printouts are clipped in all of them. A software CutePDF writer prints it to PDF correctly.
Any help appreciated.
It seems that Windows 8 does not draw ui elements outside of their container bounds. This is why the printout was clipped at the bottom.
Anyway, I ended up with a code like this, which is able to print a centered bitmap on a landscape page:
printDialog.PrintTicket.PageOrientation = PageOrientation.Landscape;
printDialog.PrintTicket.PageBorderless = PageBorderless.None;
var printingCapabilities = printDialog.PrintQueue.GetPrintCapabilities(printDialog.PrintTicket);
if (printingCapabilities.PageImageableArea == null)
{
return;
}
var document = new FixedDocument();
document.DocumentPaginator.PageSize = new Size(printingCapabilities.PageImageableArea.ExtentWidth, printingCapabilities.PageImageableArea.ExtentHeight);
foreach (var imageStream in imageStreams)
{
document.Pages.Add(GeneratePageContent(imageStream, printingCapabilities, printDialog.PrintableAreaWidth, printDialog.PrintableAreaHeight));
}
try
{
printDialog.PrintDocument(document.DocumentPaginator, GlobalConstants.SoftwareName);
}
private PageContent GeneratePageContent(Stream imageStream, PrintCapabilities printingCapabilities, double paperWidth, double paperHeight)
{
imageStream.Seek(0, SeekOrigin.Begin);
var bmp = new BitmapImage();
bmp.BeginInit();
bmp.StreamSource = imageStream;
bmp.EndInit();
var margin = new Thickness();
var pageSize = new Size();
if (printingCapabilities.PageImageableArea != null)
{
margin = new Thickness(
printingCapabilities.PageImageableArea.OriginWidth,
printingCapabilities.PageImageableArea.OriginHeight,
printingCapabilities.PageImageableArea.OriginWidth,
printingCapabilities.PageImageableArea.OriginHeight);
pageSize = new Size(printingCapabilities.PageImageableArea.ExtentWidth, printingCapabilities.PageImageableArea.ExtentHeight);
}
var imageUiElement = new Image
{
Source = bmp,
Margin = margin
};
var canvas = new Grid { Width = paperWidth, Height = paperHeight };
canvas.Children.Add(imageUiElement);
var fixedPage = new FixedPage
{
Width = paperWidth,
Height = paperHeight
};
fixedPage.Children.Add(canvas);
var pageContent = new PageContent();
((IAddChild)pageContent).AddChild(fixedPage);
pageContent.Measure(pageSize);
pageContent.Arrange(new Rect(new Point(), pageSize));
pageContent.UpdateLayout();
return pageContent;
}
I'm working on a mini-game where I need to make images go from their initial position to another using a translation transformation.
The problem is: I don't know how to proceed to apply the translation.
So here's the code used to generate my images.
Image myImage1 = new Image();
myImage1.Source = new BitmapImage(new Uri("/Images/image1.png", UriKind.Relative));
myImage1.Name = "image" + index++.ToString();
myImage1.Tap += myImage_Tap;
Canvas.SetLeft(image, 200);
Canvas.SetTop(image, 600);
gameArea.Children.Add(image);
Thanks for your time.
You have two choices to move your image around. The first is using a Canvas like your code shows, but you have to make sure your element is actually within a Canvas. Is your "gameArea" a Canvas? If it's not, your code won't work. The other option is to use Transforms.
var myImage1 = new Image
{
Source = new BitmapImage(new Uri("/Images/image1.png", UriKind.Relative)),
Name = "image" + index++.ToString(),
Tap += myImage_Tap,
RenderTransform = new TranslateTransform
{
X = 200,
Y = 600
}
};
gameArea.Children.Add(image);
Now gameArea can be any type of Panel and it will work.
Note that when using a Canvas, your Top and Left will be from the upper left corner of the Canvas. When using a Transform, your X and Y will be relative to where the element would have originally be drawn.
UPDATE -- Helper class to do simple animations using a Canvas
public sealed class ElementAnimator
{
private readonly UIElement _element;
public ElementAnimator(UIElement element)
{
if (null == element)
{
throw new ArgumentNullException("element", "Element can't be null.");
}
_element = element;
}
public void AnimateToPoint(Point point, int durationInMilliseconds = 300)
{
var duration = new Duration(TimeSpan.FromMilliseconds(durationInMilliseconds));
var easing = new BackEase
{
Amplitude = .3
};
var sb = new Storyboard
{
Duration = duration
};
var animateLeft = new DoubleAnimation
{
From = Canvas.GetLeft(_element),
To = point.X,
Duration = duration,
EasingFunction = easing,
};
var animateTop = new DoubleAnimation
{
From = Canvas.GetTop(_element),
To = point.Y,
Duration = duration,
EasingFunction = easing,
};
Storyboard.SetTargetProperty(animateLeft, "(Canvas.Left)");
Storyboard.SetTarget(animateLeft, _element);
Storyboard.SetTargetProperty(animateTop, "(Canvas.Top)");
Storyboard.SetTarget(animateTop, _element);
sb.Children.Add(animateLeft);
sb.Children.Add(animateTop);
sb.Begin();
}
}
So here's what I did with your code, I took just this part and made it a function:
public void AnimateToPoint(UIElement image, Point point, int durationInMilliseconds = 300)
{
var duration = new Duration(TimeSpan.FromMilliseconds(durationInMilliseconds));
var sb = new Storyboard
{
Duration = duration
};
var animateTop = new DoubleAnimation
{
From = Canvas.GetTop(image),
To = point.Y,
Duration = duration
};
Storyboard.SetTargetProperty(animateTop, new PropertyPath("Canvas.Top")); // You can see that I made some change here because I had an error with what you gave me
Storyboard.SetTarget(animateTop, image);
sb.Children.Add(animateTop);
sb.Begin();
}
And then I made the call with:
Point myPoint = new Point(leftpos, 300); // leftpos is a variable generated randomly
AnimateToPoint(myImage, myPoint);
So now there is still a single error, and it's in the instruction "sb.Begin;".
And it says: Cannot resolve TargetProperty Canvas.Top on specified object.
I reaylly don't know how to proceed.
Thanks for your previous answer!
I'm writing a CSS sprite engine in C#, however I'm having a few issues. I create the master image, set all the properties to that then iterate the sprites and draw those to the master image. However when I come to save the master image it only appears to be just the empty master image with transparent background and none of the sprites. I'm very confused at where I'm going wrong.
The code I'm using is:
// Work out the width/height required
int max_width = 0;
int max_height = 0;
foreach(SpriteInformation sprite in sprites) {
if (max_width < (sprite.Left + greatest_width)) max_width = sprite.Left + greatest_width;
if (max_height < (sprite.Top + greatest_height)) max_height = sprite.Top + greatest_height;
}
// Create new master bitmap
Bitmap bitmap = new Bitmap(max_width,max_height,PixelFormat.Format32bppArgb);
Graphics graphics = Graphics.FromImage(bitmap);
// Set background color
SolidBrush brush;
if (cbxBackground.Checked) {
if (txtColor.Text == "") {
brush = new SolidBrush(Color.Black);
} else {
brush = new SolidBrush(pnlColor.BackColor);
}
} else {
if (txtColor.Text == "") {
brush = new SolidBrush(Color.White);
} else {
brush = new SolidBrush(pnlColor.BackColor);
}
}
//graphics.FillRectangle(brush,0,0,bitmap.Width,bitmap.Height);
bitmap.MakeTransparent(brush.Color);
graphics.Clear(brush.Color);
// Copy images into place
ImageAttributes attr = new ImageAttributes();
//attr.SetColorKey(brush.Color,brush.Color);
foreach(SpriteInformation sprite in sprites) {
Rectangle source = new Rectangle(0,0,sprite.Width,sprite.Height);
Rectangle dest = new Rectangle(sprite.Left,sprite.Top,sprite.Width,sprite.Height);
graphics.DrawImage(sprite.Sprite,dest,0,0,sprite.Width,sprite.Height,GraphicsUnit.Pixel,attr);
}
// Save image
string format = ddlFormat.Items[ddlFormat.SelectedIndex].ToString();
if (format == "PNG") {
dlgSave.Filter = "PNG Images|*.png|All Files|*.*";
dlgSave.DefaultExt = ",png";
if (dlgSave.ShowDialog() == DialogResult.OK) {
bitmap.Save(dlgSave.FileName,ImageFormat.Png);
}
} else if (format == "JPEG") {
} else {
}
What are sprite.Left and Top? If they aren't 0 that may be a problem. I think you have dest and source the wrong way round?
http://msdn.microsoft.com/en-us/library/ms142045.aspx
Try a simpler DrawImage variant if you haven't already.
e.g. DrawImage(sprite.Sprite,0,0)
You draw to "graphics", but then then you save "bitmap"? I'm not sure if that graphics internally works with your original "bitmap" object...