WPF/Path - geometry consisting of multiple lines with different line width? - wpf

I have the need for drawing in the same drawing with lines of different color, thickness etc.
I can create two instances of PathGeometry, but I can't set color on them.
I can create two instances of Path, but can't get them displayed in my control.
What am I doing wrong?
Thanks for any comments!
Anders, Denmark.
Code below only displays "collection" in my control, but I thought it could be a starting point for answers...
var pathFigure1 = new PathFigure(new Point(0, 0),
new List<PathSegment> {new LineSegment(new Point(10, 10), true)}, false);
var pathFigure2 = new PathFigure(new Point(20, 20),
new List<PathSegment> {new LineSegment(new Point(30, 30), true)}, false);
var g1 = new PathGeometry(new List<PathFigure> {pathFigure1});
var g2 = new PathGeometry(new List<PathFigure> {pathFigure2});
var p1 = new System.Windows.Shapes.Path
{
Data = g1,
Stroke = new SolidColorBrush(Color.FromRgb(0, 0, 0))
};
var p2 = new System.Windows.Shapes.Path
{
Data = g2,
Stroke = new SolidColorBrush(Color.FromRgb(170, 87, 170))
};
var content = new Canvas();
content.Children.Add(p1);
content.Children.Add(p2);
Content = content;

You have started on the right approach, a geometry defines a 'shape', so don;t worry that you cannot set its colour. A Path turns the geometry into a visual representation on the screen, so here you can set the color and stroke thickness.
Your problem is at the very last step, you are setting the content property of your control. Typically this property is used to associate some data object with a control, you then supply a template which is its visual representation.
What you need to do is add your paths as children of a panel.
For example, add a Canvas, or a Grid to your control. Then add your two paths to the Grid / Canvas via their Children collection property.

Related

WPF Clear Region on a Drawing Context?

So I am producing a transparent PNG using a DrawingContext and DrawingVisual.
Inside the DrawingContext, I drew a rectange.
I would now like to "cut out" a circle inside of the rectangle. How do I do this? I did not find any functions in drawing context to clear a region.
You can try using CombinedGeometry to combine 2 geometries (each time). It has GeometryCombineMode allowing you to specify some logic combination. In this case what you need is GeometryCombineMode.Xor. The intersection of the Rect and the Ellipse (cirlce) will be cut out. Here is the simple code demonstrating it:
DrawingVisual dv = new DrawingVisual();
using (var dc = dv.RenderOpen()) {
var rect = new Rect(0, 0, 300, 200);
var cb = new CombinedGeometry(GeometryCombineMode.Xor,
new RectangleGeometry(rect),
new EllipseGeometry(new Point(150, 100), 50, 50));
dc.DrawGeometry(Brushes.Blue, null, cb);
}
I hope you know how to render the DrawingVisual. You can use some RenderTargetBitmap to capture it into some kind of BitmapSource and then you have many ways to show this bitmap.
Here is the screenshot:
The Black region means the color is transparent.
In case you want to cut out some complex image (such as drawn text or image). You can turn the CombinedGeometry into some kind of OpacityMask (type of Brush). We can turn it into a DrawingBrush and this brush can be used as OpacityMask which can be passed into DrawingContext.PushOpacityMask method:
DrawingVisual dv = new DrawingVisual();
using (var dc = dv.RenderOpen()) {
var rect = new Rect(0, 0, 300, 200);
var cb = new CombinedGeometry(GeometryCombineMode.Xor,
new RectangleGeometry(rect),
new EllipseGeometry(new Point(150, 100), 50, 50));
var mask = new DrawingBrush(new GeometryDrawing(Brushes.Blue, null, cb));
dc.PushOpacityMask(mask);
dc.DrawImage(someImage, rect);
dc.DrawText(new FormattedText("Windows Presentation Foundation",
System.Globalization.CultureInfo.CurrentCulture,
System.Windows.FlowDirection.LeftToRight,
new Typeface("Lucida Bright"), 30, Brushes.Red){
MaxTextWidth = rect.Width,
MaxTextHeight = rect.Height,
TextAlignment = TextAlignment.Center
}, new Point());
}
Note that the rect should have the size of your whole drawing. Then positioning the hole and other drawn stuff will be exact as what you want.
Finally the DrawingVisual also has a useful property called Clip which is a Geometry. So you can prepare some CombinedGeometry and assign it to DrawingVisual.Clip property.
Suppose you already have your DrawingVisual (with some drawn stuff including text, images, ...). The following code will punch a hole through it:
//prepare the geometry, which can be considered as the puncher.
var rect = new Rect(0, 0, 300, 200);
var cb = new CombinedGeometry(GeometryCombineMode.Xor,
new RectangleGeometry(rect),
new EllipseGeometry(new Point(150, 100), 50, 50));
//punch the DrawingVisual
yourDrawingVisual.Clip = cb;

Connecting two dynamically created shapes using line shape in silverlight

Im working on flowchart kind of application in asp.net using silverlight.. Im a beginner in Silvelight, Creating the elements (Rectangle,Ellipse,Line.. ) dynamically using SHAPE and LINE Objects in codebehind (c#)
These shapes will be generated dynamically, meaning I'll be calling a Web service on the backend to determine how many objects/shapes need to be created. Once this is determined, I'll need to have the objects/shapes connected together.
how to connect dynamically created shapes with a line in Silverlight like a flowchart.
I read the below article, but its not working for me, actualHeight & actualWidth of shapes values are 0.
Connecting two shapes together, Silverlight 2
here is my MainPage.xaml
<UserControl x:Class="LightTest1.MainPage">
<Canvas x:Name="LayoutRoot" Background="White">
<Canvas x:Name="MyCanvas" Background="Red"></Canvas>
<Button x:Name="btnPush" Content="AddRectangle" Height="20" Width="80" Margin="12,268,348,12" Click="btnPush_Click"></Button>
</Canvas>
code behind MainPage.xaml.cs
StackPanel sp1 = new StackPanel();
public MainPage()
{
InitializeComponent();
sp1.Orientation = Orientation.Vertical;
MyCanvas.Children.Add(sp1);
}
Rectangle rect1;
Rectangle rect2;
Line line1;
private void btnPush_Click(object sender, RoutedEventArgs e)
{
rect1 = new Rectangle()
{
Height = 30,
Width = 30,
StrokeThickness = 3,
Stroke = new SolidColorBrush(Colors.Red),
};
sp1.Children.Add(rect1);
rect2 = new Rectangle()
{
Height = 30,
Width = 30,
StrokeThickness = 3,
Stroke = new SolidColorBrush(Colors.Red),
};
sp1.Children.Add(rect2);
connectShapes(rect1, rect2);
}
private void connectShapes(Shape s1, Shape s2)
{
var transform1 = s1.TransformToVisual(s1.Parent as UIElement);
var transform2 = s2.TransformToVisual(s2.Parent as UIElement);
var lineGeometry = new LineGeometry()
{
StartPoint = transform1.Transform(new Point(1, s1.ActualHeight / 2.0)),
EndPoint = transform2.Transform(new Point(s2.ActualWidth, s2.ActualHeight / 2.0))
};
var path = new Path()
{
Data = lineGeometry,
Stroke = new SolidColorBrush(Colors.Green),
};
sp1.Children.Add(path);
}
what I am doing in button click event is just adding two rectangle shapes and tring to connect them with a line (like flowchart).
Please suggest what is wrong in my code..
Try replacing the line
connectShapes(rect1, rect2);
with
Dispatcher.BeginInvoke(() => connectShapes(rect1, rect2));
I'm not sure of the exact reason why this works, but I believe the shapes are only rendered once control passes out of your code, and only once they are rendered do the ActualWidth and ActualHeight properties have a useful value. Calling Dispatcher.BeginInvoke calls your code a short time later; in fact, you may notice the lines being drawn slightly after the rectangles.
The TransformToVisual method behaves in much the same way as the ActualWidth and ActualHeight properties. It will return an identity transformation if the shape hasn't been rendered. Even if your lines were being drawn with a definite width and height, they would end up being drawn all on top of one another at the top-left.
I also found that I needed to add the lines to the Canvas, not the StackPanel, in order for them to be drawn over the rectangles. Otherwise the StackPanel quickly filled up with lines with a lot of space above them.

WPF, Canvas, FormattedText.BuildGeometry - why is nothing displayed?

I have a need to display text mixed with geometries - and so far I have the geometries displayed nicely (removed from example below), but the text doesn't show up at all.
I've found the example for formatted text below and think I should be able to take the buildGeometry and enclose it in a path to be shown in a canvas.
Can anybody help me see what I am doing wrong?
Thanks for any responses,
Anders, Denmark
var canvas = new Canvas();
var formattedText = new FormattedText(
"Hello world",
CultureInfo.GetCultureInfo("en-us"),
FlowDirection.LeftToRight,
new Typeface("Verdana"),
32,
Brushes.Black);
var buildGeometry = formattedText.BuildGeometry(new Point(500, 500));
var path = new System.Windows.Shapes.Path();
path.Data = buildGeometry;
canvas.Children.Add(path);
Content = canvas;
Ay caramba,
A Path needs a Stroke defined in order to show anything(!).
Apologies to all spending time on my question....
var path = new System.Windows.Shapes.Path
{
Stroke = Brushes.Black,
StrokeThickness = 1
};

How to format specific text in WPF?

I have this code that adds dotted lines under text in text box:
// Create an underline text decoration. Default is underline.
TextDecoration myUnderline = new TextDecoration();
// Create a linear gradient pen for the text decoration.
Pen myPen = new Pen();
myPen.Brush = new LinearGradientBrush(Colors.White, Colors.White, new Point(0, 0.5), new Point(1, 0.5));
myPen.Brush.Opacity = 0.5;
myPen.Thickness = 1.0;
myPen.DashStyle = DashStyles.Dash;
myUnderline.Pen = myPen;
myUnderline.PenThicknessUnit = TextDecorationUnit.FontRecommended;
// Set the underline decoration to a TextDecorationCollection and add it to the text block.
TextDecorationCollection myCollection = new TextDecorationCollection();
myCollection.Add(myUnderline);
PasswordSendMessage.TextDecorations = myCollection;
My problem is I need only the last 6 characters in the text to be formatted!
Any idea how can I achieve that?
Instead of setting the property on the entire TextBlock, create a TextRange for the last six characters and apply the formatting to that:
var end = PasswordSendMessage.ContentEnd;
var start = end.GetPositionAtOffset(-6) ?? PasswordSendMessage.ContentStart;
var range = new TextRange(start, end);
range.ApplyPropertyValue(Inline.TextDecorationsProperty, myCollection);
If PasswordSendMessage is a TextBox rather than a TextBlock, then you cannot use rich text like this. You can use a RichTextBox, in which case this technique will work but you will need to use PasswordSendMessage.Document.ContentEnd and PasswordSendMessage.Document.ContentStart instead of PasswordSendMessage.ContentEnd and PasswordSendMessage.ContentStart.
You could databind your text to the Inlines property of TextBox and make a converter to build the run collection with a seperate Run for the last 6 characters applying your decorations

Programmatically creating a toolbar in WPF

I'm trying to create a simple toolbar in WPF, but the toolbar shows up with no corresponding buttons on it, just a very thin blank white strip. Any idea what I'm doing wrong, or what the recommended procedure is? Relevant code fragments so far:
var tb = new ToolBar();
var b = new Button();
b.Command = comback;
Image myImage = new Image();
myImage.Source = new BitmapImage(new Uri("back.png", UriKind.Relative));
b.Content = myImage;
tb.Items.Add(b);
var p = new DockPanel();
//DockPanel.SetDock(mainmenu, Dock.Top);
DockPanel.SetDock(tb, Dock.Top);
DockPanel.SetDock(sb, Dock.Bottom);
//p.Children.Add(mainmenu);
p.Children.Add(tb);
p.Children.Add(sb);
Content = p;
Without a third child-element for the Dockpanel p, the 'sb' element will fill everything except for the area of tb. The ToolBar will autoSize (its Height) according to its contents.
I suggest adding a simple text button first, to check the overall layout:
var b2 = new Button();
b2.Content = "B2";
tb.Items.Add(b2);
And then investigate what is wrong with the "back.png" image.

Resources