Greetings!
I am currently working on a Silverlight project and I would like to animate a simple polygon shape (a trapezoid actually). Specifically, I woudld like to move two of the four points dynamically after some event happened. I need / want to resize and move one of the parallel sides to another position.
I admit I am rather new to Silverlight and have not found a source that could tell me wether it is even possible, not to mention how it can be done.
I have used animations before, so the general concept of storyboards and animations is not new to me. But how can I move the points of a polygon in an animation? Are there alternatives that have a similar optical effect (e.g. animating a path)?
Is there a PropertyPath I can use, similar to
P3AnimBack.SetValue(Storyboard.TargetPropertyProperty,
new PropertyPath("(Path.Data).
(PathGeometry.Figures)[0].(PathFigure.Segments)[0].
(BezierSegment.Point3)"));
, as found in a Point Animation in Silverlight 3 tutorial?
Thank you all in advance. :)
i don't know anything about Silverlight, or animations in .NET in general, but Charles Petzold did something similar:
Squaring the Circle (view animation in browser)
Animating Points and PointCollections in Silverlight (view in browser)
Animated Polyline Interpolations in Silverlight
As requested in a comment, I explain what I finally used to make my animation:
I follwed up on Animated Polyline Interpolations in Silverlight and more or less directly used this code - "stealing" the PointCollectionInterpolator.cs class.
Then I had my method to create the polygons I need and prepare animations:
private void CreatePolygon(TextBox txtbx, string prop, Color curcol)
{
PointCollectionInterpolator pci = new PointCollectionInterpolator();
pci.Points1 = new PointCollection() // Start Points
{
new Point(...),
new Point(...),
new Point(...),
new Point(...),
};
pci.Points2 = new PointCollection() // End Points
{
new Point(...),
new Point(...),
new Point(...),
new Point(...),
};
Polygon tmpply = new Polygon();
LayoutRoot.Children.Add(tmpply);
tmpply.Points = pci.InterpolatedPoints;
DoubleAnimation animpci = new DoubleAnimation();
animpci.Duration = someDuration;
animpci.From = 0.0;
animpci.To = 1.0;
Storyboard.SetTarget(animpci, pci);
Storyboard.SetTargetProperty(animpci, new PropertyPath("(Progress)"));
myStoryBoard.Children.Add(animpci);
}
And then in some random event handler, I start the animation. Additionally, so I can reuse the method, I moved the end points collection into the start points collection and update the interpolator with new end points. (Remember setting the progress to 0.0 ...) So each time the handler fires, the polygon seamlessly morphs into a new one.
private void SomeEventHandler(object sender, RoutedEventArgs e)
{
PointCollectionInterpolator polygonPCI =
this.referenceToPointCollectionInterpolator;
polygonPCI.Points1 = polygonPCI.Points2;
polygonPCI.Progress = 0.0;
polygonPCI.Points2 = getNewEndPoints();
myStoryBoard.Begin();
}
In retrospect, i would change the names from Points1 and Points2 to StartPoints and EndPoints resp.
Hope this helped. :)
Related
in my custom control i have a ContainerVisual object and a DrawingVisual under it.
I override ArrangeOverride and calculate the rectangle that i want to draw in based on the given size and the control's padding.
after that i set my ContainerVisual object's transform to the upper left corner of the rectangle so that the methods that render the drawing would not have to take account of the rectangle and assume that the drawing origin is at point 0,0.
this does not work, and the drawing is displaced. if instead i set transform of the DrawingVisual object it works and the rectangle is displayed the way it is supposed to be.
i thought that if i set transform on the container, it will automatically be applied to the visuals under it. is that so?
thanks for any help
EDIT: Updated the source code to show complete code.
class MyControl : Control
{
private readonly ContainerVisual container = new ContainerVisual();
private readonly DrawingVisual drawing = new DrawingVisual();
private Rect rect;
private void RenderDrawing()
{
using (var c = drawing.RenderOpen())
{
var p = new Pen(new SolidColorBrush(Colors.Black), 1);
c.DrawRectangle(null, p, new Rect(0, 0, rect.Width, rect.Height));
}
}
protected override Size ArrangeOverride(Size s)
{
var h = Math.Max(0, s.Height - Padding.Top - Padding.Bottom);
var w = Math.Max(0, s.Width - Padding.Left - Padding.Right);
var r = new Rect(Padding.Left, Padding.Top, w, h);
if (rect != r)
{
rect = r;
container.Clip = new RectangleGeometry(rect);
container.Transform = new TranslateTransform(rect.Left, rect.Top);
// replace the line above with the following line to make it work
// drawing.Transform = new TranslateTransform(rect.Left, rect.Top);
RenderDrawing();
}
return s;
}
protected override Visual GetVisualChild(int index)
{
return container;
}
protected override Size MeasureOverride(Size s)
{
return new Size();
}
protected override int VisualChildrenCount
{
get { return 1; }
}
public MyControl()
{
container.Children.Add(drawing);
AddVisualChild(container);
}
}
<Window x:Class="MyApp.MyWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:c="clr-namespace:MyApp"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<c:MyControl Padding="20" />
</Grid>
</Window>
Explanation of strange clipping behavior
Now that you have posted your full source code I was finally able to see what you were seeing. Your problem isn't in the transform at all: It is in the clip!
If you comment out the container.Clip assignment statement, you get identical results no matter whether you put the transform on container or drawing
If you uncommented container.Clip assignment statement, the clipping region is perfectly centered on when the drawing is transformed, but when the container is transformed the clipping area is offset, so that only the lower and right lines of the rectangle were visible (and not all of those)
The reason this occurs is that the geometry specified for container.Clip is part of the container, so it is affected by container.Transform but not drawing.Transform:
This can be better understood by looking at the upper-left corners of the container, drawing, rectangle, and clip area relative to the upper-left corner of the window:
When you set the transform on the drawing:
Container is at (0,0) relative to window (null transform)
Clip area is at (20,20) relative to window (null transform + RectangleGeometry)
Drawing is at (20,20) relative to window (null transform + TranslateTransform)
Rectangle is at (20,20) relative to window (null transform + TranslateTransform + 0,0)
When you set the transform on the container:
Container is at (20,20) relative to window (TranslateTransform)
Clip area is at (40,40) relative to window (TranslateTransform + RectangleGeometry)
Drawing is at (20,20) relative to window (TranslateTransform + null transform)
Rectangle is at (20,20) relative to window (TranslateTransform + null transform + 0,0)
So your problem isn't that the transform isn't happening: It is that the transform is moving the clip area too, so the clip area no longer coincides with the rectangle and you can only see two sides of the rectangle.
Answer given for original code (retained because it has some useful explanation)
In fact, the code you posted never uses "container" so all you will see is a blank screen.
In your actual code you are using "container" incorrectly, preventing the events from occurring in the correct sequence to cause its Transform to be picked up and passed to the MIL layer.
Remember that when a Visual has a Transform set, it is not the visual itself but that Visual's visual parent that actually handles that transform. For example, if you render a page to XPS using ReachFramework or do hit testing, the Transform on the outermost Visual is ignored.
Your understanding is correct: If your visual tree is built following all the rules, it doesn't matter whether your transform is on your "container" or your "drawing".
Since you are using Control anyway, I'm curious why you don't just let the normal UIElement-based layout system handle your layout needs.
First update (retained for the same reason)
Thanks for the code correction. It is as I suspected: You are building your visual tree incorrectly. If you are using AddVisualChild you also must also override GetVisualChild and VisuaChildrenCount. This is because Visual does not store a list of children: It is up to the subclass (your class) to do this. What is happening is:
When you call AddVisualChild the container's transform is null so that is what is passed down to MILCore.
Later when you change the container's transform, it uses its parent pointer (that was set in AddVisualChild) to signal that its transform data must be refreshed. This update requires part of the visual tree to be scanned using GetVisualChild and VisualChildrenCount.
Since you didn't implement these methods this part of the update fails.
You say you are "new to WPF." Are you aware that you are playing with some of WPF's most low-level and esoteric features, ones that would never be used in a most ordinary WPF applications? It is equivalent to starting to learn programming using machine language. Normally you would use templates with Path, Rectangle, etc for this purpose. Sometimes you might go lower level and use a DrawingBrush with a DrawingGroup containing GeometryDrawings, etc. But you would almost never go all the way down to DrawingVisual and RenderOpen! The only time you would do that is when you have huge drawings consisting of millions of individual items and so you want to bypass all the layout and structure overhead of the higher layers for absolute maximum performance.
Manipulating the visual tree yourself (AddVisualChild, etc) is also an advanced feature. I always recommend people new to WPF stick with UIElement and above for the first few months, using Control with templates. I recommend they use Path and other shape subclasses for their drawings, and use VisualBrushes when advanced drawing effects are needed.
Hope this helps.
the problem is with the container.Clip. it should be
container.Clip = new RectangleGeometry(new Rect(0, 0, w, h));
I have the same problem as the question stated in "Printing in Silverlight 4".
To get around the problem, I have tried to scale transform root of my visual tree before printing.
void document_PrintPage(object sender, PrintPageEventArgs e)
{
var renderScale = 1.0D;
if (LayoutRoot.ActualWidth > e.PrintableArea.Width)
renderScale = e.PrintableArea.Width/LayoutRoot.ActualWidth;
var scaleTransform = new ScaleTransform();
scaleTransform.ScaleX *= renderScale;
scaleTransform.ScaleY *= renderScale;
e.PageVisual = LayoutRoot;
e.PageVisual.RenderTransform = scaleTransform;
}
Now above code correctly prints out with silverlight visuals fit on a piece of paper.
The problem now is that LayoutRoot itself is now scaled down on the screen.
The question is, is there a way for me to create a clone of LayoutRoot before applying scale transform?
My walk-around is to applying the scale tranformation again after printing but I'd like to know if there is a way to clone visual tree
My goodness, thanks for the question. I had the same problem but tried to fiddle about with setting the dimensions of a container (that is already in the visual tree) to the printable area, which does not work, as another layout pass seems to be required. ScaleTransform does work here however instantly.
I'm fine with the "work around" by just doing a myContainer.ClearValue(FrameworkElement.RenderTransformProperty) in the EndPrint event. Trying to clone the visual tree will yield a plethora of other issues (I have lazy loading content etc).
Check out this link for details on silverlight object clone.
also just another idea would using xamlreader/writer to read the xaml string and creating an in-memory copy of the visual tree work.
for ex
If your xaml has button called originalbutton, using the code below you will have a copy of the button in readerLoadButton
// Save the Button to a string.
string savedButton = XamlWriter.Save(originalButton);
// Load the button
StringReader stringReader = new StringReader(savedButton);
XmlReader xmlReader = XmlReader.Create(stringReader);
Button readerLoadButton = (Button)XamlReader.Load(xmlReader);
I am creating a WPF application in .net 4.0.
Basically I want to have a map of the world (2d) where by I can place images on, depending on their country location. This map can be an image however, it would be hard to determine the co-ordinates for the location right?
Can someone provide me with the simplest way of doing this?
I would do this by placing the image/shape object in Canvas Panel (panel with coordinates system) also I would add a wpf toolkit zoomviewer to get nice panning and zooming of the map.
Then I would make a Dictionary where key is a name of the country and value is a Point where pictures should be placed.
There are many solutions to this, all depending on your design (and tastes).
In all cases, the thing to remember is that the placement of the items on the map will always be relative to the size of the map, and will need to be recalculated whenever the size of the background map is changed. This calculation will be depend on the map itself (i.e. is it a rectangle or round, is the latitude/longitude a fixed and equal grid, the layout of the map, etc.).
One possible way to set up the main window is something like this:
This assumes that there is a folder called "Resources" that contains an image called "world-map.jpg", with its Build Action set to Resource.
Then, in your code behind, you would have to have something that actually adds a new image to the map in the appropriate place.
Personally, I would probably create a class (perhaps a custom or user control) to hold the image information, including the latitude/longitude, an Image object, etc. The main window (or ViewModel) would have a collection of these objects, which would make it easier to put them in the right places when a resize occurred. For example:
public partial class Window1 : Window
{
ObservableCollection<MyMapImageClass> mapImages = new ObservableCollection<MyMapImageClass>();
public Window1()
{
InitializeComponent();
layout.SizeChanged += new SizeChangedEventHandler(layout_SizeChanged);
}
void layout_SizeChanged(object sender, SizeChangedEventArgs e)
{
foreach (MyMapImageClass mapImage in mapImages)
{
Point point = CalculateImagePosition(mapImage.latitude, mapImage.longitude);
mapImage.Image.SetValue(Canvas.LeftProperty, point.X);
mapImage.Image.SetValue(Canvas.TopProperty, point.Y);
}
}
Point CalculateImagePlacement(double latitude, double longitude)
{
Point point = new Point();
// Do the calculations appropriate to your map
point.X = LongCalculation(longitude);
point.Y = LatCalculation(latitude);
}
void PlaceImage(double latitude, double longitude)
{
Image img = new Image();
ImageSourceConverter converter = new ImageSourceConverter();
string path = "pack://application:,,,/Resources/SomeImage.png";
ImageSource source = (ImageSource)converter.ConvertFromString(path);
img.Source = source;
img.Width = 10d;
Point point = CalculateImagePlacement(latitude, longitude);
img.SetValue(Canvas.LeftProperty, point.X);
img.SetValue(Canvas.TopProperty, point.Y);
layout.Children.Add(img);
MyMapImageClass mapImage = new MyMapImageClass();
mapImage.Latitude = latitude;
mapImage.Longitude = longitude;
mapImage.Image = img;
mapImages.Add(mapImage);
}
}
I'm working on a 3D carousel of flat, square tiles that will contain information. I'm working on animating this carousel to rotate when a person presses Next and Previous buttons.
I've gotten it to work by using BeginAnimation on the Rotation property of the RotateTransform3D I applied to the carousel, but I can't seem to make a Storyboard version of the same animation work. The reason I need the Storyboard version is for the HandOffBehavior.Compose parameter because without it, multiple clicks of my next and previous buttons results in a misaligned carousel.
Here is the code for the Storyboard:
RotateTransform3D tempTransform = (RotateTransform3D)wheel.Transform;
AxisAngleRotation3D rotation = (AxisAngleRotation3D)tempTransform.Rotation;
Storyboard storyboard = new Storyboard();
DoubleAnimation animation = new DoubleAnimation();
animation.By = defaultAngle;
animation.Duration = TimeSpan.FromSeconds(.5);
Storyboard.SetTarget(animation, rotation);
Storyboard.SetTargetProperty(animation, new PropertyPath("Angle"));
storyboard.Children.Add(animation);
storyboard.Duration = animation.Duration;
storyboard.Begin(new FrameworkContentElement(), HandoffBehavior.Compose);
For some reason, this code results in absolutely nothing. I followed the examples I had to the letter, so I am quite frustrated. Any help is greatly appreciated. I am also completely open to using BeginAnimation if I can replicate HandOffBehavior.Compose.
My experience comes from 2D animation, but I guess the problem is the same.
For some stupid reason (probably relating to an unhealthy focus on XAML), Storyboards can only animate Freezable objects by looking them up by name. (See example in Storyboards Overview.) Thus although you provide a reference to your 'rotation' object when you call Storyboard.SetTarget(animation, rotation), the Storyboard only wants to remember and use a name, which it does not have.
The solution is:
Create a naming scope around the element that will govern the transform.
Call RegisterName() for each Freezable object being animated.
Pass the element to Storyboard.Begin()
Which would make your code look something like this (not tested):
FrameworkContentElement element = new FrameworkContentElement();
NameScope.SetNameScope(element, new NameScope());
RotateTransform3D tempTransform = (RotateTransform3D)wheel.Transform;
AxisAngleRotation3D rotation = (AxisAngleRotation3D)tempTransform.Rotation;
element.RegisterName("rotation", rotation);
Storyboard storyboard = new Storyboard();
DoubleAnimation animation = new DoubleAnimation();
animation.By = defaultAngle;
animation.Duration = TimeSpan.FromSeconds(.5);
Storyboard.SetTarget(animation, rotation);
Storyboard.SetTargetProperty(animation, new PropertyPath("Angle"));
storyboard.Children.Add(animation);
storyboard.Duration = animation.Duration;
storyboard.Begin(element, HandoffBehavior.Compose);
None of this is necessary in XAML because your objects are automatically registered.
EDIT: But then I worked out that you can simplify things by leaving out the Storyboard altogether:
var T = new TranslateTransform(40, 0);
Duration duration = new Duration(new TimeSpan(0, 0, 0, 1, 0);
DoubleAnimation anim = new DoubleAnimation(30, duration);
T.BeginAnimation(TranslateTransform.YProperty, anim);
I am loading an image to my silverlight application. This image will fit in a 3d model as a texture map. I need to fetch image attributes. For that I am using ImageOpened event, like this:
public MainPage()
{
BitmapImage img = new BitmapImage(new Uri("imagens/textura.jpg", UriKind.Relative));
img.ImageOpened += new EventHandler<RoutedEventArgs>(img_ImageOpened);
img.ImageFailed += new EventHandler<ExceptionRoutedEventArgs>(img_ImageFailed);
imageBrush.ImageSource = img;
InitializeComponent();
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
this.MouseLeftButtonUp += new MouseButtonEventHandler(MainPage_MouseLeftButtonUp);
(...)
and then:
private void img_ImageOpened(object sender, RoutedEventArgs e)
{
BitmapImage i = sender as BitmapImage;
ImgSize.Width = i.PixelWidth;
ImgSize.Height = i.PixelHeight;
MessageBox.Show("LOADED IMAGE SIZE\n W:" + ImgSize.Width.ToString() + " H:" + ImgSize.Height.ToString());
}
The messagebox is showing the correct values for the loaded picture. But this is running after the scene is loaded, so the size is always default (0,0) ... I don't know how to fix this. I've runned the debugger, i've noticed that the scene and the model is rendered and the picture width and height is zero. After this, the event is fired ... I can't figure it out.
Thanks in advance,
Jose'
First off this is a little confusing:-
imageBrush.ImageSource = img;
InitializeComponent();
Unless you have something quite unusual happening the imageBrush object will be null until after the InitializeComponent has run.
As to your question at a guess you load the 3D model in MainPage_Loaded. The problem then is that his happens asynchronously with the arrival of the bitmap. Hence you do not want to actually load the 3D Model until both Loaded and ImageOpened events have both occured. Note it would be dangerous to assume that ImageOpened would always happen last.
The simplest solution I can think of would be to move all your existing code in the MainPage_Loaded event to ImageOpened then move the code that fetches the image to the MainPage_Loaded. This serialises the sequence, when execution of ImageOpened you are guaranteed that the page has loaded.
Not the most sophisticated solution and doesn't make use of benefits of the asynchronous nature of SL. However it should get you going and you can assess whether there is any benefit in having Page loading and bitmap downloading operating in parallel.