Resize Custom Control after Rotation Transformation - wpf

I've got a custom control that draws a graph. A new requirement has arrived, and one part of a solution is rotating the graph. There are other changes inside the control, but these are relatively simple and won't affect this issue.
I can rotate the control as follows:
protected override void OnRender(DrawingContext drawingContext)
{
base.OnRender(drawingContext);
InitStandard();
drawXaxis();
drawYaxis();
drawZAxis();
Titles();
Generate();
drawGridLines();
if (UsedAxisType == AxisType.FloorPlot)
{
gdRootGrid.RenderTransformOrigin = new Point(.5, .5);
gdRootGrid.RenderTransform = new RotateTransform(90);
}
}
This rotates with no problem - I now need to change the width & height of the control to match the new dimensions created with the rotate. I can't do that here as setting the width & height of the control in this event causes a rendering loop.
How do I do this properly?

Try
gdRootGrid.LayoutTransform = new RotateTransform(90);
instead.

Related

WPF IScrollInfo Fixing position of a Label

I am working on implementing an ISrollInfo interface for a custom control. Simply put, I have a label in my custom control under a Canvas. I would like the label to "stay in place" when my custom control is scrolled. That is, the label needs to be always visible no matter the scrolling offset.
Now, to as a test I added this sample code
protected override Size MeasureOverride(Size constraint)
{
return new Size(1000, 50);
}
protected override Size ArrangeOverride(Size arrangeBounds)
{
double x = 50;
double y = 50;
label1.Arrange(new Rect(new Point(x, y), new Size(1000, 50)));
return arrangeBounds;
}
When I test the control (my control is put inside a ScrollViewer), the label is hidden (before and after I use the scrollbar). If I remove the override for ArrangeOverride, the label appears and scrolls around as I use the scrollbar.
Any ideas as to what I am missing?
Found it, my ArrangeOverride is on the UserControl, where I specifically only arrange the label, the canvas doesn't get arranged (i.e postion and size is not set). Now, since the label is in the canvas, you can't see it.

Custom line drawing in WPF

I'm trying to manually draw a line in WPF by overriding the OnRender method of a control and calling the DrawLine method on the given DrawingContext. I read somewhere that this method call doesn't instantly draw the line, but I can't work out how to actually cause the line to appear.
I've tried using a combination of PathGeometry, LineSegments, Line and Polyline controls. I could draw what I wanted then, but offsets weren't quite right (i.e. when drawing a line, it was fine, when drawing a polyline, everything became incorrectly offset).
Any advice on this would be great.
EDIT
Pen Code
private static readonly Pen LinePen = new Pen(new SolidColorBrush(Colors.Green), 3.0d);
private static readonly Pen WayPointPen = new Pen(new SolidColorBrush(Colors.Gray), 3.0d);
Render Code
protected override void OnRender(DrawingContext drawingContext)
{
// Draw way points
this.DrawWayPoints(drawingContext);
if (mDrawing)
{
// Draw current line
this.DrawCurrentLine(drawingContext);
}
}
private void DrawCurrentLine(DrawingContext context)
{
if(mStartPoint.HasValue && mEndPoint.HasValue)
{
// Draw the line
context.DrawLine(LinePen, mStartPoint.Value, mEndPoint.Value);
}
}
private void DrawWayPoints(DrawingContext context)
{
if (mWayPoints.Count < 2)
{
return;
}
// Draw all points
for (int i = 0; i < mWayPoints.Count - 1; i++)
{
var start = mWayPoints[i];
var end = mWayPoints[i + 1];
// Draw the line
context.DrawLine(WayPointPen, start, end);
}
}
EDIT
Test Project: http://dl.dropbox.com/u/12763956/DrawingTest.zip
(Test Project written in Visual Studio 2010)
Usage:
- Left click within the raised area to add points to the list.
- Right click to end drawing and clear points.
Note: Custom drawn lines (in OnRender override) do not appear.
There are actually two issues here. The first is your Canvas's Background covers up anything you'd draw on your DrawingControl. So if you set the Canvas Background to Transparent, you can temporarily work around that issue.
The second issue is you need to call InvalidateVisual after you add a point to your collection to force it to redraw.
You would probably need to add another control that appears on top of the Canvas, and render the lines there. Or you'd need to render the Background yourself in the DrawingControl.OnRender method.

WPF Control moves but its Adorner - Not :"/

I created an adorner on a WPF line element, because there was neet to add some text.
Now, when this line is moved, the adorner does not "follow" the line automatically. In fact, it does not refresh itsef:
here black curves is the Control drawing, and the red "120 m" is the adorner one.
Some code
void SegmentLine_Loaded(object sender, RoutedEventArgs e)
{
AdornerLayer aLayer = AdornerLayer.GetAdornerLayer(this);
if (aLayer != null)
{
aLayer.Add(new TextAdorner(this));
}
}
class TextAdorner : Adorner
{
public TextAdorner(UIElement adornedElement)
: base(adornedElement)
{
}
protected override void OnRender(DrawingContext drawingContext)
{
SegmentLine segment = (this.AdornedElement as SegmentLine);
if (segment != null)
{
Rect segmentBounds = new Rect(segment.DesiredSize);
var midPoint = new Point(
(segment.X1 + segment.X2) / 2.0,
(segment.Y1 + segment.Y2) / 2.0);
var lineFont = // get line font as Font
FormattedText ft = new FormattedText(
string.Format("{0} m", segment.Distance),
Thread.CurrentThread.CurrentCulture,
System.Windows.FlowDirection.LeftToRight,
new Typeface(lineFont.FontFamily.ToString()),
ligneFont.Size, Brushes.Red);
drawingContext.DrawText(ft, midPoint);
}
}
}
Why MeasureOverride, etc aren't being called
Your adorner's MeasureOverride, ArrangeOverride, and OnRender aren't being called because your SegmentLine control is never changing size or position:
Since your SegmentLine doesn't implement MeasureOverride, it always has the default size assigned by the layout engine.
Since your SegmentLine doesn't implement ArrangeOverride or manipulate any transforms, its position is always exactly the upper-left corner of the container.
The Adorner's MeasureOverride, ArrangeOverride and OnRender are only called by WPF under these conditions:
The AdornedElement changes size or position (this the most common case), or
One of the Adorner's properties chagnes and that property is marked AffectsMeasure, AffectsArrange, or AffectsRender, or
You call InvalidateMeasure(), InvalidateArrange(), or InvalidateVisuaul() on the adorner.
Because your SegmentLine never changes size or position, case 1 doesn't apply. Since you don't have any such properties on the Adorner and don't call InvalidateMeasure(), InvalidateArrange() or InvalidateVisual(), the other cases don't apply either.
Precise rules for Adorner re-measure
Here are the precise rules for when an adorned element change triggers a call to Adorner.MeasureOverride:
The adorned element must force a layout pass by invalidating its Measure or Arrange in response to some event. This could be triggered automatically by a change to a DependencyProperty with AffectsMeasure or AffectsArrange, or by a direct call to InvalidateMeasure(), InvalidateArrange() or InvalidateVisual().
The adorned element's Measure and Arrange methods must not be called directly from user code between the invalidation and the layout pass. In other words, you must wait for the layout manager to do the job.
The adorned element must make a non-trivial change to either its RenderSize or its Transform.
The combination of all transforms between the AdornerLayer and the adorned element must be affine. This will generally be the case as long as you are not using 3D.
Your SegmentLine is just drawing the line in a new place rather than updating its own dimensions, thereby omitting my requirement #3 above.
Recommendation
Normally I would recommend your adorner have AffectsRender DependencyProperties bound to the SegmentLine's properties, so any time X1, Y1, etc change in the SegmentLine they are also updated in the Adorner which causes the Adorner to re-render. This provides a very clean interface, since the adorner can be used on any control that has properties X1, Y1, etc, but it is less efficient than tightly coupling them.
In your case the adorner is clearly tightly bound to your SegmentLine, so I think it makes just as much sense to call InvalidateVisual() on the adorner from the SegmentLine's OnRender(), like this:
public class SegmentLine : Shape
{
TextAdorner adorner;
...
protected override void OnRender(DrawingContext drawingContext)
{
base.OnRender(drawingContext);
if(adorner==null)
{
var layer = AdornerLayer.GetAdornerLayer(this); if(layer==null) return;
adorner = new TextAdorner(this);
... set other adorner properties and events ...
layer.Add(adorner);
}
adorner.InvalidateVisual();
}
}
Note that this doesn't deal with the situation where the SegmentLine is removed from the visual tree and then added again later. Your original code doesn't deal with this either, so I avoided the complexity of dealing with that case. If you need that to work, do this instead:
public class SegmentLine : Shape
{
AdornerLayer lastLayer;
TextAdorner adorner;
...
protected override void OnRender(DrawingContext drawingContext)
{
base.OnRender(drawingContext);
var layer = AdornerLayer.GetAdornerLayer(this);
if(layer!=lastLayer)
{
if(adorner==null)
{
adorner = new TextAdorner(this);
... set other adorner properties and events ...
}
if(lastLayer!=null) lastLayer.Remove(adorner);
if(layer!=null) layer.Add(adorner);
lastLayer = layer;
}
adorner.InvalidateVisual();
}
}
How is the line being moved? Does the MeasureOverride or ArrangeOverride of the adorner get invoked after the move? OnRender will only get invoked if the visual is invalidated (e.g. invalidatevisual) so I'm guessing that the render isn't being invalidated.
May be you wanted to use segmentBounds to define midPoint? Otherwise what is it doing there? Looks like you are defining midPoint relative to not rerendered segment.
idiot fix, but it works
AdornerLayer aLayer;
void SegmentLine_Loaded(object sender, RoutedEventArgs e)
{
aLayer = AdornerLayer.GetAdornerLayer(this);
if (aLayer != null)
{
aLayer.Add(new TextAdorner(this));
}
}
protected override void OnRender(DrawingContext drawingContext)
{
base.OnRender(drawingContext);
if (aLayer != null)
{
aLayer.Update();
}
}
Now, the problem is that when I click on a the adorner the control itself does not recieve the hit...

problem with ContainerVisual.Transform

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));

Removing the render transform of a child element

Ok,
So I have a situation, where an border is being scaled (sometimes by a large amount) and translated. Inside the border is a grid, and inside the grid are two images, one is a photo and is stretched to the size of the border, and the other, I intend on being an icon, which needs to be a fixed size in the bottom left hand corner.
The problem is, that I want to remove the effect scaling is having on the icon. This is because I've given the icon a fixed size and would like it to remain that size, but unfortunately the scaling from the border is propagating down the the children of the border and effecting them also.
So I've tried using an attached property, similar to this pixel snapping artical (http://blogs.msdn.com/b/devdave/archive/2008/06/22/using-an-attached-dependencyproperty-to-implement-pixel-snapping-as-an-attached-behavior.aspx), but it doesn't seem to make a difference. When steped through, the elements which are being modified in LayoutUpdate always seem to have the identity matrix for the render transform anyway, before I've set it.
I guess I'm miss-interperating how render transforms are applied to children maybe?
Anyway, this is what I have (Also, I know this (if it worked) would remove translation too, which isn't what I want!):
public static readonly DependencyProperty IsConstantSizeProperty =
DependencyProperty.RegisterAttached(
"ConstantWidth",
typeof(bool),
typeof(ItemsControlEX),
new PropertyMetadata(new PropertyChangedCallback(IsConstantSizeChanged)));
private static List<FrameworkElement> m_constSizeObjects = new List<FrameworkElement>();
private static void IsConstantSizeChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
bool isConstantWidth = (bool)args.NewValue;
if (isConstantWidth)
{
FrameworkElement el = (FrameworkElement)obj;
m_constSizeObjects.Add(el);
el.LayoutUpdated += new EventHandler(el_LayoutUpdated);
el.Unloaded += new RoutedEventHandler(el_Unloaded);
}
}
static void el_Unloaded(object sender, RoutedEventArgs e)
{
FrameworkElement el = (FrameworkElement)sender;
el.Unloaded -= new RoutedEventHandler(el_Unloaded);
el.LayoutUpdated -= new EventHandler(el_LayoutUpdated);
m_constSizeObjects.Remove(el);
}
static void el_LayoutUpdated(object sender, EventArgs e)
{
foreach (FrameworkElement el in m_constSizeObjects)
{
MatrixTransform trans = new MatrixTransform();
trans.Matrix = Matrix.Identity;
el.RenderTransform = trans;
}
}
public static void SetIsConstantWidth(UIElement element, Boolean value)
{
element.SetValue(IsConstantSizeProperty, value);
}
public static Boolean GetIsConstantWidth(UIElement element)
{
return (Boolean)element.GetValue(IsConstantSizeProperty);
}
I'm thinking I'm probably thinking about this in completely the wrong way maybe. I guess the sensible solution would be to refactor to remove the need for scaling, but I guess I was just after a quicker solution that I can use until I have time.
Any help is appreciated! :)
Thanks!
Andy.
If you are only scaling (I assume fixed aspect ratio) that seems overly complicated, why not place the photo in a ViewBox container? Place the ViewBox (containing the photo) and the icon (in that order) in a parent grid.
Make the icon relative to the bottom
left using alignment and margin
settings
Resize the viewbox to scale your image.
The grid will shrink to fit the viewbox size. The icon will remain relative to the grid bottom-left.
Your pixel snapping behaviour should work on a ViewBox.
If you need a specific example, please provide some of your Xaml to work from.

Resources