private void DetermineHorizontalPopupOffset() { double widthOffset = -9.0; //unknown why we need this offset var words = Text.Split( new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries ); string textBeforeLastWord = words.Length > 1 ? string.Join(" ", words.Take(words.Length - 1)) + " " : null; if (string.IsNullOrEmpty(textBeforeLastWord)) { HorizontalPopupOffset = widthOffset; } else { var textBlock = new TextBlock { Text = textBeforeLastWord }; textBlock.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); double desiredWidth = textBlock.DesiredSize.Width; HorizontalPopupOffset = desiredWidth - 1 + widthOffset; } }
public static WriteableBitmap GetTextWriteableBitmap(string text, Orientation orientation = Orientation.Horizontal) { var txtBlock = new TextBlock(); txtBlock.Text = text; // 1) get current dpi PresentationSource pSource = PresentationSource.FromVisual(Application.Current.MainWindow); Matrix m = pSource.CompositionTarget.TransformToDevice; double _dpiX = m.M11 * 96; double _dpiY = m.M22 * 96; txtBlock.Measure(new Size(double.MaxValue, double.MaxValue)); txtBlock.Arrange(new Rect(new Point(0, 0), new Size(double.MaxValue, double.MaxValue))); var sz = txtBlock.DesiredSize; // 2) create RenderTargetBitmap var elementBitmap = new RenderTargetBitmap((int)sz.Width, (int)sz.Height, _dpiX, _dpiY, PixelFormats.Default); // 3) undo element transformation var drawingVisual = new DrawingVisual(); using (var dc = drawingVisual.RenderOpen()) { var visualBrush = new VisualBrush(txtBlock); dc.DrawRectangle(visualBrush, null, new Rect(new Point(0, 0), sz)); } // 4) draw element elementBitmap.Render(drawingVisual); var wb = new WriteableBitmap(elementBitmap); if (orientation == Orientation.Vertical) { wb = wb.Rotate(270); } return(wb); }
public static void UpdateInlines(this TextBlock textBlock, IFontManager fontManager, FormattedString formattedString, double defaultLineHeight = 0d, TextAlignment defaultHorizontalAlignment = TextAlignment.Start, Font?defaultFont = null, Color?defaultColor = null, TextTransform defaultTextTransform = TextTransform.Default) { textBlock.Inlines.Clear(); // Have to implement a measure here, otherwise inline.ContentStart and ContentEnd will be null, when used in RecalculatePositions textBlock.Measure(new global::Windows.Foundation.Size(double.MaxValue, double.MaxValue)); var runAndColorTuples = formattedString.ToRunAndColorsTuples(fontManager, defaultLineHeight, defaultHorizontalAlignment, defaultFont, defaultColor, defaultTextTransform); var heights = new List <double>(); int currentTextIndex = 0; foreach (var runAndColorTuple in runAndColorTuples) { Run run = runAndColorTuple.Item1; Color textColor = runAndColorTuple.Item2; Color background = runAndColorTuple.Item3; heights.Add(textBlock.FindDefaultLineHeight(run)); textBlock.Inlines.Add(run); int length = run.Text.Length; if (background != null || textColor != null) { TextHighlighter textHighlighter = new TextHighlighter { Ranges = { new TextRange(currentTextIndex, length) } }; if (background != null) { textHighlighter.Background = background.ToPlatform(); } if (textColor != null) { textHighlighter.Foreground = textColor.ToPlatform(); } textBlock.TextHighlighters.Add(textHighlighter); } currentTextIndex += length; } }
/// <summary> /// 输出报表项内容 /// </summary> protected override void DoOutput() { RptText item = _item as RptText; RptRootInst root = Inst; root.OutputItem(this); ParseValue(); if (!item.AutoHeight || _region.RowSpan > 1) { return; } // 处理自动行高 double height = 0; Kit.RunSync(() => { // 测量文本的实际高度 TextBlock tb = new TextBlock(); tb.TextWrapping = item.WordWrap ? TextWrapping.Wrap : TextWrapping.NoWrap; tb.FontFamily = new FontFamily(item.FontFamily); tb.FontSize = item.FontSize; if (item.Bold) { tb.FontWeight = FontWeights.Bold; } if (item.Italic) { tb.FontStyle = FontStyle.Italic; } tb.Text = Text; tb.Width = Width - 8 - item.Margin * 2; tb.Measure(new Size(double.MaxValue, double.MaxValue)); height = Math.Ceiling(tb.ActualHeight) + 4; }); root.SyncRowHeight(this, height); }
protected override Size MeasureOverride(Size availableSize) { Size returnedSize = new Size(0, 0); //we do not need space mainTextBlock.Measure(new Size(double.MaxValue, double.MaxValue)); if (double.IsInfinity(availableSize.Height) || (availableSize.Height > mainTextBlock.DesiredSize.Height)) { // there is enough space, we return our minimum space returnedSize.Height = mainTextBlock.DesiredSize.Height; } if (double.IsInfinity(availableSize.Width) || (availableSize.Width > mainTextBlock.DesiredSize.Width)) { // there is enough space, we return our minimum space returnedSize.Width = mainTextBlock.DesiredSize.Width; } return(returnedSize); /* * mainTextBlock.Visibility = Visibility.Collapsed; * if (availableSize.Height < initialheight) * { * //if the is not enough height for the text, * //return new Size(0, availableSize.Height); * } * else * { * //return new Size(0, initialheight); * } * * return new Size(0, 0); * // Size baseSize = base.MeasureOverride(availableSize); * // return baseSize; * */ }
/// <summary> /// Measures the size of the specified text. /// </summary> /// <param name="text">The text.</param> /// <param name="fontFamily">The font family.</param> /// <param name="fontSize">Size of the font (in device independent units, 1/96 inch).</param> /// <param name="fontWeight">The font weight.</param> /// <returns> /// The size of the text (in device independent units, 1/96 inch). /// </returns> public OxySize MeasureText(string text, string fontFamily, double fontSize, double fontWeight) { if (string.IsNullOrEmpty(text)) { return(OxySize.Empty); } if (this.TextMeasurementMethod == TextMeasurementMethod.GlyphTypeface) { return(this.MeasureTextByGlyphTypeface(text, fontFamily, fontSize, fontWeight)); } var tb = new TextBlock { Text = text }; TextOptions.SetTextFormattingMode(tb, this.TextFormattingMode); if (fontFamily != null) { tb.FontFamily = new FontFamily(fontFamily); } if (fontSize > 0) { tb.FontSize = fontSize; } if (fontWeight > 0) { tb.FontWeight = GetFontWeight(fontWeight); } tb.Measure(new Size(1000, 1000)); return(new OxySize(tb.DesiredSize.Width, tb.DesiredSize.Height)); }
void ReadStream(Stream file, Encoding enc) { using (var reader = new StreamReader(file, enc, false, 0x400, true)) { this.Document.Blocks.Clear(); var para = new Paragraph(); var block = new TextBlock(); block.FontFamily = this.Document.FontFamily; block.FontSize = this.Document.FontSize; block.Padding = this.Document.PagePadding; double max_width = 0; var max_size = new Size(double.PositiveInfinity, double.PositiveInfinity); for (;;) { var line = reader.ReadLine(); if (null == line) { break; } if (line.Length > 0) { block.Text = line; block.Measure(max_size); var width = block.DesiredSize.Width; if (width > max_width) { max_width = width; } para.Inlines.Add(new Run(line)); } para.Inlines.Add(new LineBreak()); } this.Document.Blocks.Add(para); MaxLineWidth = max_width; ApplyWordWrap(IsWordWrapEnabled); } }
void UpdateText() { if (Text == null || FontFamily == null || FontWeight == null || FontStyle == null) { return; } _textBlocks = new TextBlock[Text.Length]; _segmentLengths = new double[Text.Length]; for (int i = 0; i < Text.Length; i++) { TextBlock t = new TextBlock(); t.FontSize = this.FontSize; t.FontFamily = this.FontFamily; t.FontStretch = this.FontStretch; t.FontWeight = this.FontWeight; t.FontStyle = this.FontStyle; if (Inverted) { t.Text = new String(Text[i], 1); t.LayoutTransform = new RotateTransform(angle: 0); } else { t.Text = new String(Text[(Text.Length - 1) - i], 1); t.LayoutTransform = new RotateTransform(angle: 180); } t.RenderTransformOrigin = new Point(0.0, 1.0); t.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); _textBlocks[i] = t; _segmentLengths[i] = t.DesiredSize.Width; } }
///<summary>生成Y方向大小的标注</summary> private void genSizeYLabel() { if (SizeYName != null) { Point pb1, pb2, po1, po2, pomid, pomid2, pend; GeneralTransform3DTo2D gtransform = owner.modelMain.TransformToAncestor(owner.grdMain); Model3D lModel = model.model; pb1 = gtransform.Transform(new Point3D(lModel.Bounds.X, lModel.Bounds.Y + lModel.Bounds.SizeY, (lModel.Bounds.Z + lModel.Bounds.SizeZ) / 2)); pb2 = gtransform.Transform(new Point3D(lModel.Bounds.X, lModel.Bounds.Y, (lModel.Bounds.Z + lModel.Bounds.SizeZ) / 2)); po1 = pb1; po1.Offset(-10, 0); po2 = pb2; po2.Offset(-10, 0); pomid = new Point((po1.X + po2.X) / 2, (po1.Y + po2.Y) / 2); pomid2 = pomid; pomid2.Offset(-20, 0); pend = pomid2; pend.Offset(-10, -10); Path path; path = new Path() { StrokeThickness = 1, Stroke = Brushes.White }; path.Data = getPathGeo(pb1, pb2, po1, po2, pomid, pomid2, pend); owner.grdFlag.Children.Add(path); path = new Path() { StrokeThickness = 1, Fill = Brushes.Blue }; path.Data = new EllipseGeometry(pend, 5, 5); owner.grdFlag.Children.Add(path); TextBlock txt = new TextBlock() { Foreground = new SolidColorBrush(Color.FromRgb(0x66, 0xFF, 0xCC)), VerticalAlignment = VerticalAlignment.Top, HorizontalAlignment = HorizontalAlignment.Left }; txt.Text = SizeYName; txt.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity)); txt.Margin = new Thickness(pend.X - txt.DesiredSize.Width / 2, pend.Y - txt.DesiredSize.Height - 5, 0, 0); owner.grdFlag.Children.Add(txt); } }
public NodeNameAdornernment(UIElement adornedElement, Node adornedNode) : base(adornedElement) { if (adornedNode == null) { return; } AdornedNode = adornedNode; visualChildren = new VisualCollection(this); var text = AdornedNode.Name + " Node"; label = new TextBlock { IsHitTestVisible = false, Text = text, Margin = new Thickness(0), FontSize = 12, FontWeight = FontWeights.Bold, LineStackingStrategy = LineStackingStrategy.MaxHeight, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center }; label.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); border = new Border { IsHitTestVisible = false, Background = Brushes.AliceBlue, BorderThickness = new Thickness(1), BorderBrush = Brushes.Gray, Padding = new Thickness(0), MaxWidth = 200, Child = label, Width = label.DesiredSize.Width + MarginAroundLabel * 2, Height = label.DesiredSize.Height + MarginAroundLabel * 2 }; visualChildren.Add(border); }
private void Button_OnClick(object sender, RoutedEventArgs e) { PrintDialog printDialog = new PrintDialog(); if (printDialog.ShowDialog() == true) { // Create the text. Run run = new Run("This is a test of the printing functionality " + "in the Windows Presentation Foundation."); // Wrap it in a TextBlock. TextBlock visual = new TextBlock(); visual.Inlines.Add(run); // Use margin to get a page border. visual.Margin = new Thickness(15); // Allow wrapping to fit the page width. visual.TextWrapping = TextWrapping.Wrap; // Scale the TextBlock up in both dimensions by a factor of 5. // (In this case, increasing the font would have the same effect, // because the TextBlock is the only element.) visual.LayoutTransform = new ScaleTransform(5, 5); // Size the element. Size pageSize = new Size(printDialog.PrintableAreaWidth, printDialog.PrintableAreaHeight); visual.Measure(pageSize); visual.Arrange(new Rect(0, 0, pageSize.Width, pageSize.Height)); // Print the element. printDialog.PrintVisual(visual, "A Scaled Drawing"); } }
public static void GenerateXLabels(this ICanvasRange range, double leftOffset) { for (double dx = range.Xmin; dx <= range.Xmax; dx += range.XTick) { Point pt = range.NormalizePoint(new Point(dx, range.Ymin)); Line tick = new Line { Stroke = Brushes.Black, X1 = pt.X, Y1 = pt.Y, X2 = pt.X, Y2 = pt.Y - 5 }; range.ChartCanvas.Children.Add(tick); TextBlock tb = new TextBlock { Text = dx.ToString() }; tb.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity)); range.TextCanvas.Children.Add(tb); Canvas.SetLeft(tb, leftOffset + pt.X - tb.DesiredSize.Width / 2); Canvas.SetTop(tb, pt.Y + 2 + tb.DesiredSize.Height / 2); } }
public static void GenerateYLabels(this ICanvasRange range) { for (double dy = range.Ymin; dy <= range.Ymax; dy += range.YTick) { Point pt = range.NormalizePoint(new Point(range.Xmin, dy)); Line tick = new Line { Stroke = Brushes.Black, X1 = pt.X, Y1 = pt.Y, X2 = pt.X + 5, Y2 = pt.Y }; range.ChartCanvas.Children.Add(tick); TextBlock tb = new TextBlock { Text = dy.ToString() }; tb.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity)); range.TextCanvas.Children.Add(tb); Canvas.SetRight(tb, range.ChartCanvas.Width + 10); Canvas.SetTop(tb, pt.Y); } }
private void cmdPrint_Click(object sender, RoutedEventArgs e) { PrintDialog printDialog = new PrintDialog(); if (printDialog.ShowDialog() == true) { // Create the text. Run run = new Run("This is a test of the printing functionality in the Windows Presentation Foundation."); // Wrap it in a TextBlock. TextBlock visual = new TextBlock(run); visual.Margin = new Thickness(15); // Allow wrapping to fit the page width. visual.TextWrapping = TextWrapping.Wrap; // Scale the TextBlock in both dimensions. double zoom; if (Double.TryParse(txtScale.Text, out zoom)) { visual.LayoutTransform = new ScaleTransform(zoom / 100, zoom / 100); // Get the size of the page. Size pageSize = new Size(printDialog.PrintableAreaWidth, printDialog.PrintableAreaHeight); // Trigger the sizing of the element. visual.Measure(pageSize); visual.Arrange(new Rect(0, 0, pageSize.Width, pageSize.Height)); // Print the element. printDialog.PrintVisual(visual, "A Scaled Drawing"); } else { MessageBox.Show("Invalid scale value."); } } }
private static YogaSize MeasureTextInput(ReactTextInputShadowNode textInputNode, YogaNode node, float width, YogaMeasureMode widthMode, float height, YogaMeasureMode heightMode) { var normalizedWidth = Math.Max(0, (YogaConstants.IsUndefined(width) ? double.PositiveInfinity : width)); var normalizedHeight = Math.Max(0, (YogaConstants.IsUndefined(height) ? double.PositiveInfinity : height)); var normalizedText = string.IsNullOrEmpty(textInputNode._text) ? " " : textInputNode._text; var textBlock = new TextBlock { Text = normalizedText, TextWrapping = textInputNode._multiline ? TextWrapping.Wrap : TextWrapping.NoWrap, }; ApplyStyles(textInputNode, textBlock); textBlock.Measure(new Size(normalizedWidth, normalizedHeight)); return(MeasureOutput.Make( (float)Math.Ceiling(width), (float)Math.Ceiling(textBlock.ActualHeight))); }
public int stringWidth(string s, TextBlock tb) { if (width.ContainsKey(s)) { return(width[s]); } int response = 0; using (AutoResetEvent are = new AutoResetEvent(false)) { System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => { applyFont(tb); tb.Text = s; tb.Measure(new Size(10000, 10000)); response = (int)System.Math.Round(tb.DesiredSize.Width); width.Add(s, response); are.Set(); }); are.WaitOne(); } return(response); }
/// <summary> /// 根据文字得到控件的宽度和高度 /// </summary> /// <param name="txtValue"></param> /// <returns></returns> private Size GetSize(string txtValue) { TextBlock tb = new TextBlock(); if (string.IsNullOrEmpty(txtValue)) { txtValue = "0"; } tb.Text = txtValue; tb.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); //可以得到tb.ActualWidth,tb.ActualHeight为文本的实际宽高 double perLen = tb.ActualWidth / tb.Text.Length; //每个字符的宽度 double actualWidth = tb.ActualHeight; if (tb.Text.Length > 1) { actualWidth = tb.ActualHeight + (tb.Text.Length - 1) * perLen; } if (actualWidth < tb.ActualHeight) { actualWidth = tb.ActualHeight; } return(new Size(actualWidth, tb.ActualHeight)); }
private void AdjustFontSizes() { var buttons = GetButtonList(); var shortEdge = buttons[0].ActualHeight; if (shortEdge > buttons[0].ActualWidth) { shortEdge = buttons[0].ActualWidth; } var tb = new TextBlock(); tb.FontFamily = buttons[0].FontFamily; tb.FontSize = shortEdge * 0.8; tb.Text = "g"; tb.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity)); var height = tb.DesiredSize.Height; foreach (Button button in buttons) { button.FontSize = height; } }
public void UpdateNode(EntityViewModel node) { var drawingNode = this.Graph.FindNode(node.Model.Id.ToString()); if (drawingNode is null) { return; } // update the underlying label drawingNode.Label.Text = node.Name; // remasure the node var tb = new TextBlock { Text = node.Name }; tb.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); drawingNode.GeometryNode.BoundingBox = new GeometryRectangle(0, 0, tb.DesiredSize.Width, tb.DesiredSize.Height) { Center = drawingNode.GeometryNode.BoundingBox.Center }; }
private void Annotation_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName.Equals("Mode")) { LabelVM annotaiton = sender as LabelVM; if (annotaiton != null && annotaiton.Mode == ContentEditorMode.View) { TextBlock textblock = new TextBlock(); textblock.RenderTransformOrigin = new Point(0.5, 0.5); textblock.Width = this.UnitWidth; textblock.Text = annotaiton.Content.ToString(); textblock.TextWrapping = annotaiton.WrapText; textblock.FontStyle = annotaiton.FontStyle; textblock.FontSize = annotaiton.FontSize; textblock.Foreground = annotaiton.LabelForeground; textblock.FontWeight = annotaiton.FontWeight; textblock.FontFamily = annotaiton.Font; textblock.HorizontalAlignment = annotaiton.HorizontalAlignment; textblock.VerticalAlignment = annotaiton.VerticalAlignment; textblock.TextAlignment = annotaiton.TextHorizontalAlignment; textblock.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); } } }
private static YogaSize MeasureText(ReactTextShadowNode textNode, YogaNode node, float width, YogaMeasureMode widthMode, float height, YogaMeasureMode heightMode) { // This is not a terribly efficient way of projecting the height of // the text elements. It requires that we have access to the // dispatcher in order to do measurement, which, for obvious // reasons, can cause perceived performance issues as it will block // the UI thread from handling other work. // // TODO: determine another way to measure text elements. var task = DispatcherHelpers.CallOnDispatcher(() => { var textBlock = new TextBlock { TextAlignment = TextAlignment.Left, TextWrapping = TextWrapping.Wrap, TextTrimming = TextTrimming.CharacterEllipsis, }; textNode.UpdateTextBlockCore(textBlock, true); for (var i = 0; i < textNode.ChildCount; ++i) { var child = textNode.GetChildAt(i); textBlock.Inlines.Add(ReactInlineShadowNodeVisitor.Apply(child)); } var normalizedWidth = YogaConstants.IsUndefined(width) ? double.PositiveInfinity : width; var normalizedHeight = YogaConstants.IsUndefined(height) ? double.PositiveInfinity : height; textBlock.Measure(new Size(normalizedWidth, normalizedHeight)); return(MeasureOutput.Make( (float)Math.Ceiling(textBlock.DesiredSize.Width), (float)Math.Ceiling(textBlock.DesiredSize.Height))); }); return(task.Result); }
/// <summary> /// Creates the visual appearance of a label /// </summary> private void Render(IRenderContext context, ILabel label, VisualGroup container, IOrientedRectangle labelLayout, RenderDataCache cache) { // store information with the visual on how we created it container.SetRenderDataCache(cache); // background rectangle System.Windows.Shapes.Rectangle rect = new System.Windows.Shapes.Rectangle { Width = labelLayout.Width, Height = labelLayout.Height, RadiusX = labelLayout.Width / 10, RadiusY = labelLayout.Height / 10, Stroke = Brushes.SkyBlue, Fill = fillBrush, StrokeThickness = 1 }; container.Add(rect); // TextBlock with label text TextBlock textBlock = new TextBlock { Text = cache.LabelText, FontFamily = cache.Typeface.FontFamily, FontStretch = cache.Typeface.Stretch, FontStyle = cache.Typeface.Style, FontWeight = cache.Typeface.Weight, Foreground = Brushes.Black, }; textBlock.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity)); // if edit button is visible align left, otherwise center double textPositionLeft = cache.ButtonVisibility == Visibility.Visible ? HorizontalInset : (labelLayout.Width - textBlock.DesiredSize.Width) / 2; textBlock.SetCanvasArrangeRect(new Rect(textPositionLeft, (labelLayout.Height - textBlock.DesiredSize.Height) / 2, textBlock.DesiredSize.Width, textBlock.DesiredSize.Height )); container.Add(textBlock); //////////////////////////////////////////////////// //////////////// New in this sample //////////////// //////////////////////////////////////////////////// if (cache.ButtonVisibility == Visibility.Visible) { // get style for edit button from XAML resources // create edit button Button editLabelButton = new Button { Style = editButtonStyle }; editLabelButton.SetCanvasArrangeRect(new Rect(labelLayout.Width - HorizontalInset - ButtonSize, VerticalInset, ButtonSize, ButtonSize)); // set button command editLabelButton.Command = GraphCommands.EditLabel; editLabelButton.CommandParameter = label; editLabelButton.CommandTarget = context.CanvasControl; container.Add(editLabelButton); } //////////////////////////////////////////////////// }
/// <summary> /// Allows the TextBlock to determine how big it wants to be. /// </summary> /// <param name="constraint">A limiting size for the TextBlock.</param> protected override Size MeasureOverride(Size constraint) { _textBlock.Measure(constraint); return(_textBlock.DesiredSize); }
/// <summary> /// Construct page with header and footer. /// </summary> /// <param name="pageNumber">The current page to transform.</param> /// <returns>The document page.</returns> private DocumentPage ConstructPageWithHeaderAndFooter(int pageNumber) { DocumentPage page0 = flowDocPaginator.GetPage(pageNumber); // Coming from WPFNotepad, the source document should always be a FlowDocument FlowDocument originalDocument = (FlowDocument)flowDocPaginator.Source; TextBlock headerBlock = null; TextBlock footerBlock = null; DocumentPage newPage = null; if (originalPageSize == Size.Empty) { originalPageSize = ((IDocumentPaginatorSource)originalDocument).DocumentPaginator.PageSize; } Size newPageSize = originalPageSize; // Decrease the top and/or bottom margins to account for headers/footers if ((headerText != null) && (headerText.Length > 0)) { string expandedHeaderText = GetExpandedText(headerText, originalDocument, pageNumber + 1); headerBlock = new TextBlock(); headerBlock.Text = expandedHeaderText; headerBlock.FontFamily = SystemFonts.MenuFontFamily; headerBlock.FontSize = 10; headerBlock.HorizontalAlignment = HorizontalAlignment.Center; headerBlock.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity)); headerBlock.Arrange(new Rect(headerBlock.DesiredSize)); headerBlock.UpdateLayout(); if (headerBlock.DesiredSize.Width > 0 && headerBlock.DesiredSize.Height > 0) { newPageSize.Height -= headerBlock.DesiredSize.Height; } } if ((footerText != null) && (footerText.Length > 0)) { string expandedFooterText = GetExpandedText(footerText, originalDocument, pageNumber + 1); footerBlock = new TextBlock(); footerBlock.Text = expandedFooterText; footerBlock.FontFamily = SystemFonts.MenuFontFamily; footerBlock.FontSize = 10; footerBlock.HorizontalAlignment = HorizontalAlignment.Center; footerBlock.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity)); footerBlock.Arrange(new Rect(footerBlock.DesiredSize)); footerBlock.UpdateLayout(); if (footerBlock.DesiredSize.Width > 0 && footerBlock.DesiredSize.Height > 0) { newPageSize.Height -= footerBlock.DesiredSize.Height; } } // Get the original page with its reduced size flowDocPaginator.PageSize = newPageSize; DocumentPage page = flowDocPaginator.GetPage(pageNumber); if (page != DocumentPage.Missing) { // Create a Grid that will hold the header, the original page, and the footer Grid grid = new Grid(); RowDefinition rowDef = new RowDefinition(); rowDef.Height = new GridLength(0, GridUnitType.Auto); grid.RowDefinitions.Add(rowDef); rowDef = new RowDefinition(); rowDef.Height = new GridLength(0, GridUnitType.Star); grid.RowDefinitions.Add(rowDef); rowDef = new RowDefinition(); rowDef.Height = new GridLength(0, GridUnitType.Auto); grid.RowDefinitions.Add(rowDef); ColumnDefinition columnDef = new ColumnDefinition(); grid.ColumnDefinitions.Add(columnDef); // The header and footer TextBlocks can be added to the grid // directly. The Visual from the original DocumentPage needs // to be hosted in a container that derives from UIElement. if (headerBlock != null) { headerBlock.Margin = new Thickness(0, originalDocument.PagePadding.Top, 0, 0); Grid.SetRow(headerBlock, 0); grid.Children.Add(headerBlock); } VisualContainer container = new VisualContainer(); container.PageVisual = page.Visual; container.PageSize = newPageSize; Grid.SetRow(container, 1); grid.Children.Add(container); if (footerBlock != null) { footerBlock.Margin = new Thickness(0, 0, 0, originalDocument.PagePadding.Bottom); Grid.SetRow(footerBlock, 2); grid.Children.Add(footerBlock); } // Recalculate the children inside the Grid grid.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity)); grid.Arrange(new Rect(grid.DesiredSize)); grid.UpdateLayout(); // Return the new DocumentPage constructed from the Grid's Visual newPage = new DocumentPage(grid); } // Return the page. return(newPage); }
private void RefreshTicks() { //return; TicksCanvas.Children.RemoveRange(0, TicksCanvas.Children.Count); var deltaX = MaxX - MinX; var deltaY = MaxY - MinY; if (!(deltaX > 0 && deltaY > 0)) { return; } var miniStepX = 10; var stepX = 50; if (deltaX > 100) { miniStepX = 20; stepX = 100; } var miniStepY = 2; var stepY = 10; if (deltaY > 100) { miniStepY = 10; stepY = 50; } if (deltaY > 500) { miniStepY = 50; stepY = 100; } if (deltaY > 2000) { miniStepY = 100; stepY = 500; } if (deltaY > 10000) { miniStepY = 1000; stepY = 5000; } //foreach (var point in dataPoints) //{ // var x = deltaX > 0 ? Normalize(width * ((point.WaveLength - MinX) / deltaX), width, 1) : width / 2; // var y = deltaY > 0 ? Normalize(height * (1 - (point.Intencity - MinY) / deltaY), height, 1) : height / 2; // yield return new Tuple<Point, ISpectrometerDataPoint>(new Point(x, y), point); //} var startOffsetX = MinX % miniStepX; var endOffsetX = MaxX % miniStepX; for (var currentX = (int)(MinX - MinX % miniStepX + miniStepX); currentX < MaxX; currentX += miniStepX) { var x = GraphCanvas.ActualWidth * (currentX - MinX) / deltaX; var isStepX = currentX % stepX == 0; if (isStepX) { var textBlock = new TextBlock { Text = currentX.ToString(), Foreground = _blackBrush, FontSize = 12, Background = _whiteBrush, TextAlignment = TextAlignment.Right }; textBlock.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity)); var size = textBlock.DesiredSize; TicksCanvas.Children.Add(textBlock); Canvas.SetLeft(textBlock, x - size.Width / 2); Canvas.SetTop(textBlock, GraphCanvas.ActualHeight + _tickHeight + 2); } TicksCanvas.Children.Add(new Line { X1 = x, X2 = x, Y1 = GraphCanvas.ActualHeight, Y2 = GraphCanvas.ActualHeight + _tickHeight, Stroke = _blackBrush, StrokeThickness = isStepX ? 1 : .5 }); //TicksCanvas.Children.Add(new Line //{ // X1 = x, // X2 = x, // Y1 = 0, // Y2 = GraphCanvas.ActualHeight, // Stroke = _greyBrush, // StrokeDashArray = new DoubleCollection() { 1, 1 }, // StrokeThickness = isStepX ? 2 : 1 //}); } for (var currentY = (int)(MinY - MinY % miniStepY + miniStepY); currentY < MaxY; currentY += miniStepY) { var y = GraphCanvas.ActualHeight * (1 - (currentY - MinY) / deltaY); var isStepY = currentY % stepY == 0; if (isStepY) { var textBlock = new TextBlock { Text = currentY.ToString(), Foreground = _blackBrush, FontSize = 12, Background = _whiteBrush, TextAlignment = TextAlignment.Right }; textBlock.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity)); var size = textBlock.DesiredSize; TicksCanvas.Children.Add(textBlock); Canvas.SetLeft(textBlock, -size.Width - 2 - _tickHeight); Canvas.SetTop(textBlock, y - size.Height / 2); } TicksCanvas.Children.Add(new Line { Y1 = y, Y2 = y, X1 = 0, X2 = -_tickHeight, Stroke = _blackBrush, StrokeThickness = isStepY ? 1 : .5 }); //TicksCanvas.Children.Add(new Line //{ // Y1 = y, // Y2 = y, // X1 = 0, // X2 = GraphCanvas.ActualWidth, // Stroke = _greyBrush, // StrokeDashArray = new DoubleCollection() { 1, 1 }, // StrokeThickness = isStepY ? 2 : 1 //}); } }
/// <summary> /// Draws the text. /// </summary> /// <param name="p">The position.</param> /// <param name="text">The text.</param> /// <param name="fill">The fill color.</param> /// <param name="fontFamily">The font family.</param> /// <param name="fontSize">Size of the font.</param> /// <param name="fontWeight">The font weight.</param> /// <param name="rotate">The rotation angle.</param> /// <param name="halign">The horizontal alignment.</param> /// <param name="valign">The vertical alignment.</param> /// <param name="maxSize">The maximum size of the text.</param> public void DrawText( ScreenPoint p, string text, OxyColor fill, string fontFamily, double fontSize, double fontWeight, double rotate, OxyPlot.HorizontalAlignment halign, OxyPlot.VerticalAlignment valign, OxySize?maxSize) { var tb = new TextBlock { Text = text, Foreground = new SolidColorBrush(fill.ToColor()) }; // tb.SetValue(TextOptions.TextHintingModeProperty, TextHintingMode.Animated); if (fontFamily != null) { tb.FontFamily = new FontFamily(fontFamily); } if (fontSize > 0) { tb.FontSize = fontSize; } tb.FontWeight = GetFontWeight(fontWeight); tb.Measure(new Size(1000, 1000)); var size = new Size(tb.ActualWidth, tb.ActualHeight); if (maxSize != null) { if (size.Width > maxSize.Value.Width) { size.Width = maxSize.Value.Width; } if (size.Height > maxSize.Value.Height) { size.Height = maxSize.Value.Height; } tb.Clip = new RectangleGeometry { Rect = new Rect(0, 0, size.Width, size.Height) }; } double dx = 0; if (halign == OxyPlot.HorizontalAlignment.Center) { dx = -size.Width / 2; } if (halign == OxyPlot.HorizontalAlignment.Right) { dx = -size.Width; } double dy = 0; if (valign == OxyPlot.VerticalAlignment.Middle) { dy = -size.Height / 2; } if (valign == OxyPlot.VerticalAlignment.Bottom) { dy = -size.Height; } var transform = new TransformGroup(); transform.Children.Add(new TranslateTransform { X = (int)dx, Y = (int)dy }); if (!rotate.Equals(0)) { transform.Children.Add(new RotateTransform { Angle = rotate }); } transform.Children.Add(new TranslateTransform { X = (int)p.X, Y = (int)p.Y }); tb.RenderTransform = transform; this.ApplyTooltip(tb); if (this.clip) { // add a clipping container that is not rotated var c = new Canvas(); c.Children.Add(tb); this.Add(c); } else { this.Add(tb); } }
public override object createFont(int face, int style, int size) { if (fontCache.ContainsKey(face | style | size)) { return fontCache[face | style | size]; } int a = 24; switch (size) { case 8: //com.codename1.ui.Font._fSIZE_1SMALL: a = 15; break; case 16: //com.codename1.ui.Font._fSIZE_1LARGE: a = 56; break; } NativeFont nf = new NativeFont(); nf.height = a; nf.systemFace = face; nf.systemSize = size; nf.systemStyle = style; using (AutoResetEvent are = new AutoResetEvent(false)) { System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => { TextBlock tb = new TextBlock(); tb.FontSize = nf.height; tb.Text = "Xp"; tb.Measure(new Size(1000000, 1000000)); nf.actualHeight = (int)tb.ActualHeight; are.Set(); }); are.WaitOne(); } if ((style & com.codename1.ui.Font._fSTYLE_1BOLD) == com.codename1.ui.Font._fSTYLE_1BOLD) { nf.bold = true; } if ((style & com.codename1.ui.Font._fSTYLE_1ITALIC) == com.codename1.ui.Font._fSTYLE_1ITALIC) { nf.italic = true; } fontCache[face | style | size] = nf; return nf; }
public override int stringWidth(java.lang.Object n1, java.lang.String n2) { NativeFont font = f(n1); string str = toCSharp(n2); StringFontPair sfp = new StringFontPair(str, font); if (stringWidthCache.ContainsKey(sfp)) { return stringWidthCache[sfp]; } int result = 0; using (AutoResetEvent are = new AutoResetEvent(false)) { System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => { TextBlock tb = new TextBlock(); tb.FontSize = font.height; tb.Text = str; tb.Measure(new Size(1000000, 1000000)); result = (int)tb.ActualWidth; are.Set(); }); are.WaitOne(); } stringWidthCache.Add(sfp, result); return result; }
// Lines that make the graph private void UpdateDividers() { // Add the background lines dividers double divXSize = GraphCanvas.Width / (numDividersX + 1); if (horzDividersVisible) { for (int i = 1; i < numDividersX + 1; i++) { Rectangle rect = new Rectangle(); rect.Width = dividerThickness; rect.Height = GraphCanvas.Height; rect.Fill = new SolidColorBrush(dividerColor); Canvas.SetLeft(rect, i * divXSize); Canvas.SetTop(rect, 0); GraphCanvas.Children.Add(rect); } } double divYSize = GraphCanvas.Height / (numDividersY + 1); if (vertDividersVisible) { for (int i = 1; i < numDividersY + 1; i++) { Rectangle rect = new Rectangle(); rect.Width = GraphCanvas.Width; rect.Height = dividerThickness; rect.Fill = new SolidColorBrush(dividerColor); Canvas.SetLeft(rect, 0); Canvas.SetTop(rect, GraphCanvas.Height - i * divYSize); GraphCanvas.Children.Add(rect); } } // Add text labels on divider positions double rangeY = (end.Y - start.Y) / (numDividersY + 1); for (int i = 0; i < numDividersY + 2; i++) { // Add a vertical axis label TextBlock label = new TextBlock(); label.Foreground = new SolidColorBrush(labelColor); label.FontSize = vertLabelFontSize; string str = getVertLabelStr(i); if (str == "") { label.Text = (start.Y + i * rangeY).ToString() + vertLabelSuffix; } else { label.Text = str; } label.FontFamily = new FontFamily("Assets/AGENCYB.TTF#Agency FB"); label.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); Canvas.SetLeft(label, -label.DesiredSize.Width - 3); Canvas.SetTop(label, GraphCanvas.Height - i * divYSize - label.DesiredSize.Height * 0.45); MainCanvas.Children.Add(label); } double rangeX = (end.X - start.X) / (numDividersX + 1); for (int i = 0; i < numDividersX + 2; i++) { // Add a horizontal axis label TextBlock label = new TextBlock(); label.Foreground = new SolidColorBrush(labelColor); label.FontSize = horzLabelFontSize; string str = getHorzLabelStr(i); if (str == "") { label.Text = (start.X + i * rangeX).ToString() + horzLabelSuffix; } else { label.Text = str; } label.FontFamily = new FontFamily("Assets/AGENCYB.TTF#Agency FB"); label.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); Canvas.SetLeft(label, i * divXSize - label.DesiredSize.Width * 0.45); Canvas.SetTop(label, WeatherGraphBorder.Height + label.DesiredSize.Height * 0.7); MainCanvas.Children.Add(label); } }
public void ExtTextOut(Canvas surface, double x, double y, ExtTextOutOptions options, Rect dimensions, string text, double[] dx) { TextBlock block = null; Grid container = null; double deviceX = LtoDX(x); double deviceY = LtoDY(y); double textWidth; double textHeight; Geometry clipGeometry = null; if (dx == null) { // No character placement block = new TextBlock { Inlines = { new Run { Text = text } } }; ApplyTextStyle(block, deviceY, true, options); //Canvas.SetLeft(block, deviceX); surface.Children.Add(block); block.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); textHeight = block.DesiredSize.Height; textWidth = block.DesiredSize.Width; } else { // Place individual characters int stringLength = text.Length; double currentPos = 0; // LtoDX(x); container = new Grid(); for (int i = 0; i < stringLength; i++) { block = new TextBlock { Inlines = { new Run { Text = text.Substring(i, 1) } } }; //TextOptions.SetTextFormattingMode(block, TextFormattingMode.Display); ApplyTextStyle(block, deviceY, false, null); if (i > 0) { currentPos += ScaleWidth(dx[i - 1]); } block.Margin = new Thickness(currentPos, 0, 0, 0); // TODO: Character width //block.Width = dx[i]; container.Children.Add(block); } //Canvas.SetLeft(container, deviceX); ApplyTextContainerStyle(container, deviceY); surface.Children.Add(container); container.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); textHeight = container.DesiredSize.Height; textWidth = container.DesiredSize.Width; } // Horizontal alignment if ((_currentState.TextAlign & (ushort)TextAlignmentMode.TA_CENTER) == (ushort)TextAlignmentMode.TA_CENTER) { deviceX -= textWidth / 2.0; } else if ((_currentState.TextAlign & (ushort)TextAlignmentMode.TA_RIGHT) == (ushort)TextAlignmentMode.TA_RIGHT) { deviceX -= textWidth; } // Vertical Alignment if ((_currentState.TextAlign & (ushort)TextAlignmentMode.TA_BASELINE) == (ushort)TextAlignmentMode.TA_BASELINE) { double baseline; #if NETFX_CORE baseline = textHeight; #else if (block != null) { var formattedText = new FormattedText( text, System.Globalization.CultureInfo.CurrentCulture, block.FlowDirection, new Typeface(block.FontFamily, block.FontStyle, block.FontWeight, block.FontStretch, block.FontFamily), block.FontSize, block.Foreground); baseline = formattedText.Baseline; } else { baseline = textHeight; } #endif deviceY -= baseline; } else if ((_currentState.TextAlign & (ushort)TextAlignmentMode.TA_BOTTOM) == (ushort)TextAlignmentMode.TA_BOTTOM) { deviceY -= textHeight; } // Clip clipGeometry = GetClipGeometryAsChild( new Rect( deviceX, deviceY, textWidth, textHeight) ); if (container == null) { Canvas.SetLeft(block, deviceX); Canvas.SetTop(block, deviceY); #if !NETFX_CORE if (clipGeometry != null) { block.Clip = clipGeometry; } #endif } else { Canvas.SetLeft(container, deviceX); Canvas.SetTop(container, deviceY); #if !NETFX_CORE if (clipGeometry != null) { container.Clip = clipGeometry; } #endif } if ((options & ExtTextOutOptions.ETO_OPAQUE) == ExtTextOutOptions.ETO_OPAQUE) { block.Height = ScaleHeight(dimensions.Height); block.Width = ScaleWidth(dimensions.Width); } //if ((currentState.TextAlign & (ushort)TextAlignmentMode.TA_UPDATECP) == (ushort)TextAlignmentMode.TA_UPDATECP) //{ // // Update current pos // Point pos = currentState.CurrentPosition; // // TODO: Mapx and y // pos.X = Canvas.GetLeft(block) + block.ActualWidth; // pos.Y = Canvas.GetTop(block) + block.ActualHeight; // currentState.CurrentPosition = pos; //} }
static System.Drawing.SizeF StringSize(string text, int fontSize, FontFamily fontFamily, bool bold) { TextBlock txtMeasure = new TextBlock(); txtMeasure.FontFamily = fontFamily; txtMeasure.FontSize = fontSize; txtMeasure.FontWeight = bold ? Windows.UI.Text.FontWeights.Bold : Windows.UI.Text.FontWeights.Normal; txtMeasure.Text = text; txtMeasure.Measure (new Size (1, 1)); return new System.Drawing.SizeF((float)txtMeasure.ActualWidth, (float)txtMeasure.ActualHeight); }
/// <summary> /// Draws the text. /// </summary> /// <param name="p">The position.</param> /// <param name="text">The text.</param> /// <param name="fill">The fill color.</param> /// <param name="fontFamily">The font family.</param> /// <param name="fontSize">Size of the font.</param> /// <param name="fontWeight">The font weight.</param> /// <param name="rotate">The rotation angle.</param> /// <param name="halign">The horizontal alignment.</param> /// <param name="valign">The vertical alignment.</param> /// <param name="maxSize">The maximum size of the text.</param> public void DrawText( ScreenPoint p, string text, OxyColor fill, string fontFamily, double fontSize, double fontWeight, double rotate, OxyPlot.HorizontalAlignment halign, OxyPlot.VerticalAlignment valign, OxySize? maxSize) { var tb = new TextBlock { Text = text, Foreground = new SolidColorBrush(fill.ToColor()) }; // tb.SetValue(TextOptions.TextHintingModeProperty, TextHintingMode.Animated); if (fontFamily != null) { tb.FontFamily = new FontFamily(fontFamily); } if (fontSize > 0) { tb.FontSize = fontSize; } tb.FontWeight = GetFontWeight(fontWeight); tb.Measure(new Size(1000, 1000)); var size = new Size(tb.ActualWidth, tb.ActualHeight); if (maxSize != null) { if (size.Width > maxSize.Value.Width) { size.Width = maxSize.Value.Width; } if (size.Height > maxSize.Value.Height) { size.Height = maxSize.Value.Height; } tb.Clip = new RectangleGeometry { Rect = new Rect(0, 0, size.Width, size.Height) }; } double dx = 0; if (halign == OxyPlot.HorizontalAlignment.Center) { dx = -size.Width / 2; } if (halign == OxyPlot.HorizontalAlignment.Right) { dx = -size.Width; } double dy = 0; if (valign == OxyPlot.VerticalAlignment.Middle) { dy = -size.Height / 2; } if (valign == OxyPlot.VerticalAlignment.Bottom) { dy = -size.Height; } var transform = new TransformGroup(); transform.Children.Add(new TranslateTransform { X = (int)dx, Y = (int)dy }); if (!rotate.Equals(0)) { transform.Children.Add(new RotateTransform { Angle = rotate }); } transform.Children.Add(new TranslateTransform { X = (int)p.X, Y = (int)p.Y }); tb.RenderTransform = transform; this.ApplyTooltip(tb); if (this.clip) { // add a clipping container that is not rotated var c = new Canvas(); c.Children.Add(tb); this.Add(c); } else { this.Add(tb); } }
void SeriesAxis_AnnoCreated(object sender, AnnoCreatedEventArgs e) { var ax = (Axis)sender; LegendItem li = null; var isFar = (Position & AxisPosition.Far) != 0; // find legend item if (_chart != null) { foreach (var item in _chart.LegendItems) { if (item.Item == _series) { li = item; break; } } } // label color if (li != null) { var tb = e.Label as TextBlock; if (tb != null) { tb.Foreground = li.Symbol.Fill; } } if (e.Index == 0 && _series != null) { var slbl = new TextBlock() { Text = _series.Label, VerticalAlignment = VerticalAlignment.Center }; // display symbol if (li != null) { slbl.Foreground = li.Symbol.Fill; Canvas.SetLeft(li.Symbol, -12); Canvas.SetTop(li.Symbol, 6); e.Canvas.Children.Add(li.Symbol); } // show label slbl.Measure(new Size(10000, 10000)); Canvas.SetLeft(slbl, 0); Canvas.SetTop(slbl, 0); e.Canvas.Children.Add(slbl); e.Canvas.Tag = GetPosition(slbl); if (!isFar) { slbl.RenderTransform = new RotateTransform() { Angle = 180, CenterX = 0.5 * slbl.ActualWidth, CenterY = 0.5 * slbl.ActualHeight + 2 }; } slbl.MouseLeftButtonDown += (s, args) => { args.Handled = true; MessageBox.Show(string.Format("Clicked on axis label = {0}", _series.Label)); }; } // hide label if it is overlapped with series label if (e.Canvas.Tag is Rect) { var tb = e.Label as FrameworkElement; var rect = (Rect)e.Canvas.Tag; rect.Intersect(GetPosition(tb)); e.Cancel = !rect.IsEmpty; } // e.Canvas.ClipToBounds = false; // handle clicking of label if (!e.Cancel) { e.Label.MouseLeftButtonDown += (s, args) => { if (e.Label is TextBlock) { MessageBox.Show(string.Format("Clicked on axis = {0} at label = {1}", _series.Label, ((TextBlock)e.Label).Text)); } args.Handled = true; }; } }
public void AddColorBar(ChartStyle cs, DataSeriesSurface ds, double zmin, double zmax) { TextBlock tb; tb = new TextBlock(); tb.Text = "A"; tb.FontFamily = cs.TickFont; tb.FontSize = cs.TickFontSize; tb.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity)); Size tickSize = tb.DesiredSize; double x = 6 * cs.ChartCanvas.Width / 7; double y = cs.ChartCanvas.Height / 10; double width = cs.ChartCanvas.Width / 25; double height = 8 * cs.ChartCanvas.Height / 10; Point3D[] pts = new Point3D[64]; double dz = (zmax - zmin) / 63; // Create the color bar: Polygon plg; for (int i = 0; i < 64; i++) { pts[i] = new Point3D(x, y, zmin + i * dz); } for (int i = 0; i < 63; i++) { SolidColorBrush brush = GetBrush(pts[i].Z, zmin, zmax); double y1 = y + height - (pts[i].Z - zmin) * height / (zmax - zmin); double y2 = y + height - (pts[i + 1].Z - zmin) * height / (zmax - zmin); plg = new Polygon(); plg.Points.Add(new Point(x, y2)); plg.Points.Add(new Point(x + width, y2)); plg.Points.Add(new Point(x + width, y1)); plg.Points.Add(new Point(x, y1)); plg.Fill = brush; plg.Stroke = brush; cs.ChartCanvas.Children.Add(plg); } Rectangle rect = new Rectangle(); rect.Width = width + 2; rect.Height = height + 2; rect.Stroke = Brushes.Black; Canvas.SetLeft(rect, x - 1); Canvas.SetTop(rect, y - 1); cs.ChartCanvas.Children.Add(rect); // Add ticks and labels to the color bar: double tickLength = 0.15 * width; for (double z = zmin; z <= zmax; z = z + (zmax - zmin) / 6) { double yy = y + height - (z - zmin) * height / (zmax - zmin); AddTickLine(cs, new Point(x, yy), new Point(x + tickLength, yy)); AddTickLine(cs, new Point(x + width, yy), new Point(x + width - tickLength, yy)); tb = new TextBlock(); tb.Text = (Math.Round(z, 2)).ToString(); tb.FontFamily = cs.TickFont; tb.FontSize = cs.TickFontSize; cs.ChartCanvas.Children.Add(tb); Canvas.SetLeft(tb, x + width + 5); Canvas.SetTop(tb, yy - tickSize.Height / 2); } }
/// <summary> /// Measures the text. /// </summary> /// <param name="text">The text.</param> /// <param name="fontFamily">The font family.</param> /// <param name="fontSize">Size of the font.</param> /// <param name="fontWeight">The font weight.</param> /// <returns>The text size.</returns> public OxySize MeasureText(string text, string fontFamily, double fontSize, double fontWeight) { if (string.IsNullOrEmpty(text)) { return OxySize.Empty; } var tb = new TextBlock { Text = text }; if (fontFamily != null) { tb.FontFamily = new FontFamily(fontFamily); } if (fontSize > 0) { tb.FontSize = fontSize; } tb.FontWeight = GetFontWeight(fontWeight); tb.Measure(new Size(1000, 1000)); return new OxySize(tb.ActualWidth, tb.ActualHeight); }
public void DrawLegend(Canvas canvas) { TextBlock tb = new TextBlock(); if (this.lines.Count < 1) { return; } double legendWidth = 0.0d; Size size = new Size(0.0d, 0.0d); foreach (LineData l in this.lines) { tb = new TextBlock(); tb.Text = l.Name; tb.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity)); size = tb.DesiredSize; if (legendWidth < size.Width) { legendWidth = size.Width; } } legendWidth += 20.0d; canvas.Width = legendWidth + 5.0d; double legendHeight = 25.0d * this.lines.Count; double sx = 5.0d; double sy = 0.0d; double textHeight = size.Height; double lineLength = 34.0d; Rectangle legendRect = new Rectangle(); legendRect.Stroke = Brushes.Black; legendRect.Fill = Brushes.White; legendRect.Width = legendWidth + 18.0d; legendRect.Height = legendHeight; canvas.Children.Add(legendRect); Rectangle rect; int n = 1; foreach (LineData l in this.lines) { double xText = 2.0d * sx + lineLength; double yText = n * sy + (2.0d * n - 1.0d) * textHeight / 2.0d; rect = new Rectangle(); rect.Stroke = Brushes.Black; rect.StrokeThickness = this.strokeThickness; rect.Fill = l.Color; rect.Width = 10.0d; rect.Height = 10.0d; Canvas.SetLeft(rect, sx + lineLength / 2.0d - 15.0d); Canvas.SetTop(rect, yText - 2.0d); canvas.Children.Add(rect); tb = new TextBlock(); tb.Text = l.Name; canvas.Children.Add(tb); Canvas.SetTop(tb, yText - size.Height / 2.0d + 3.0d); Canvas.SetLeft(tb, xText - 20.0d); n++; } canvas.Width = legendRect.Width; canvas.Height = legendRect.Height; }
static System.Drawing.SizeF StringSize(string text, int fontSize) { TextBlock txtMeasure = new TextBlock(); txtMeasure.FontSize = fontSize; txtMeasure.Text = text; txtMeasure.Measure (new Size (1, 1)); return new System.Drawing.SizeF((float)txtMeasure.ActualWidth, (float)txtMeasure.ActualHeight); }