public void LoadHtmlDarkByName() { TextRenderer renderer = new TextRenderer(new Lexer()); renderer.Configure("HtmlDark"); Assert.AreEqual("<span style=\"color: lightgreen\">", renderer.GetFormat("StringBegin")); Assert.AreEqual("</span>", renderer.GetFormat("StringEnd")); }
void buildGumpling(int x, int y, int hue, string text) { Position = new Point2D(x, y); Hue = hue; Text = text; _textRenderer = new TextRenderer(Text, 0, true); _textRenderer.Hue = Hue; }
void buildGumpling(int x, int y, int width, int height, int hue, int textIndex, string[] lines) { Position = new Point2D(x, y); Size = new Point2D(width, height); Hue = hue; Text = lines[textIndex]; _textRenderer = new TextRenderer(Text, width, true); }
public void GetPlainTextWithSimpleRenderer() { TextRenderer renderer = new TextRenderer(new Lexer()); string text = "foreach (var k in values) {"; var result = renderer.Render(text); Assert.AreEqual(text, result); }
public ChatLineTimed(string text, int width) { m_text = text; m_isExpired = false; m_alpha = 1.0f; m_width = width; m_renderer = new TextRenderer(m_text, m_width, true); }
public Reader(TextSource textSource, TextRenderer textRenderer, double maxWPM) { this.maxWPM = maxWPM; this.textRenderer = textRenderer; this.textSource = textSource; this.wordTimer = new Timer(START_WORD_INTERVAL); wordTimer.Elapsed += new ElapsedEventHandler(wordTimerHandler); }
public GameplayScreen(ContentManager globalContent, UIScreenService uiScreenService) : base("Content/UI/Screens/GameplayScreen", "GameplayScreen", globalContent) { Contract.Require(uiScreenService, "uiScreenService"); this.textRenderer = new TextRenderer(); this.blankTexture = GlobalContent.Load<Texture2D>(GlobalTextureID.Blank); this.photograph = GlobalContent.Load<Texture2D>(GlobalTextureID.Photograph); this.font = GlobalContent.Load<SpriteFont>(GlobalFontID.SegoeUI); }
public void TextTable_RendersFromViewModel() { const Int32 TablePadding = 4; const Int32 TableOffset = 32; var spriteBatch = default(SpriteBatch); var spriteFont = default(SpriteFont); var textRenderer = default(TextRenderer); var table = default(TextTable<TextTableViewModel>); var tableLayout = default(TextTableLayout); var tableTexture = default(Texture2D); var result = GivenAnUltravioletApplication() .WithContent(content => { spriteBatch = SpriteBatch.Create(); spriteFont = content.Load<SpriteFont>("Fonts/SegoeUI"); textRenderer = new TextRenderer(); textRenderer.RegisterFont("header", content.Load<SpriteFont>("Fonts/Garamond")); textRenderer.RegisterFont("text", content.Load<SpriteFont>("Fonts/SegoeUI")); tableTexture = Texture2D.Create(1, 1); tableTexture.SetData(new[] { Color.White }); tableLayout = content.Load<TextTableLayout>("Tables/TestTextTable"); table = tableLayout.Create<TextTableViewModel>(textRenderer, spriteFont); table.ViewModel = new TextTableViewModel() { Name = "Legendary Item of Power", Description = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean feugiat dui nec dui interdum, a bibendum odio pellentesque. Ut cursus neque eros, nec luctus ligula euismod a.", Type = "Weapon", Subtype = "Ranged" }; }) .Render(uv => { uv.GetGraphics().Clear(Color.Magenta); spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend); table.PerformLayout(); spriteBatch.Draw(tableTexture, new RectangleF(TableOffset, TableOffset, table.ActualWidth + (TablePadding * 2), table.ActualHeight + (TablePadding * 2)), Color.Black * 0.75f); table.Draw(spriteBatch, Vector2.One * (TableOffset + TablePadding)); spriteBatch.End(); }); TheResultingImage(result). ShouldMatch(@"Resources\Expected\Graphics\Graphics2D\Text\TextTable_RendersFromViewModel.png"); }
public SampleScreen2(ContentManager globalContent, UIScreenService uiScreenService) : base("Content/UI/Screens/SampleScreen2", "SampleScreen2", globalContent) { Contract.Require(uiScreenService, "uiScreenService"); IsOpaque = true; this.font = LocalContent.Load<SpriteFont>("Garamond"); this.blankTexture = GlobalContent.Load<Texture2D>(GlobalTextureID.Blank); this.textRenderer = new TextRenderer(); }
public void GetTextWithNames() { TextRenderer renderer = new TextRenderer(new Lexer()); renderer.SetFormat("NameBegin", "<name>"); renderer.SetFormat("NameEnd", "</name>"); string text = "foreach (var k in values) {"; var result = renderer.Render(text); Assert.AreEqual("<name>foreach</name> (<name>var</name> <name>k</name> <name>in</name> <name>values</name>) {", result); }
public void GetTextWithPuntuation() { TextRenderer renderer = new TextRenderer(new Lexer()); renderer.SetFormat("PunctuationBegin", "<pt>"); renderer.SetFormat("PunctuationEnd", "</pt>"); string text = "foreach (var k in values) {"; var result = renderer.Render(text); Assert.AreEqual("foreach <pt>(</pt>var k in values<pt>)</pt> <pt>{</pt>", result); }
public void GetTextWithTextBeginAndEd() { TextRenderer renderer = new TextRenderer(new Lexer()); renderer.SetFormat("TextBegin", "<div>\r\n"); renderer.SetFormat("TextEnd", "\r\n</div>\r\n"); string text = "foreach (var k in values) {"; var result = renderer.Render(text); Assert.AreEqual("<div>\r\nforeach (var k in values) {\r\n</div>\r\n", result); }
public void DrawObject(SpriteBatch batch, bool debug = false, TextRenderer rend = null, TextLayoutSettings settings = new TextLayoutSettings()) { if(debug) { if (rend != null) { rend.Draw(batch, "yo", body2D.GetPosition().ToScreenVector(), TwistedLogik.Ultraviolet.Color.Gold, settings); } else { Console.WriteLine("Hey yo you didn't give me a TextRenderer"); } } }
/// <summary> /// The application implemented rendering callback (<see cref="TextRenderer.DrawInlineObject"/>) can use this to draw the inline object without needing to cast or query the object type. The text layout does not call this method directly. /// </summary> /// <param name="clientDrawingContext">The drawing context passed to <see cref="SharpDX.DirectWrite.TextLayout.Draw_"/>. This parameter may be NULL. </param> /// <param name="renderer">The same renderer passed to <see cref="SharpDX.DirectWrite.TextLayout.Draw_"/> as the object's containing parent. This is useful if the inline object is recursive such as a nested layout. </param> /// <param name="originX">The x-coordinate at the upper-left corner of the inline object. </param> /// <param name="originY">The y-coordinate at the upper-left corner of the inline object. </param> /// <param name="isSideways">A Boolean flag that indicates whether the object's baseline runs alongside the baseline axis of the line. </param> /// <param name="isRightToLeft">A Boolean flag that indicates whether the object is in a right-to-left context and should be drawn flipped. </param> /// <param name="clientDrawingEffect">The drawing effect set in <see cref="SharpDX.DirectWrite.TextLayout.SetDrawingEffect"/>. Usually this effect is a foreground brush that is used in glyph drawing. </param> /// <returns>If the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code. </returns> /// <unmanaged>HRESULT IDWriteInlineObject::Draw([None] void* clientDrawingContext,[None] IDWriteTextRenderer* renderer,[None] float originX,[None] float originY,[None] BOOL isSideways,[None] BOOL isRightToLeft,[None] IUnknown* clientDrawingEffect)</unmanaged> public void Draw(object clientDrawingContext, TextRenderer renderer, float originX, float originY, bool isSideways, bool isRightToLeft, ComObject clientDrawingEffect) { var handle = GCHandle.Alloc(clientDrawingContext); IntPtr clientDrawingEffectPtr = Utilities.GetIUnknownForObject(clientDrawingEffect); try { this.Draw__(GCHandle.ToIntPtr(handle), TextRendererShadow.ToIntPtr(renderer), originX, originY, isSideways, isRightToLeft, clientDrawingEffectPtr); } finally { if (handle.IsAllocated) handle.Free(); if (clientDrawingEffectPtr != IntPtr.Zero) Marshal.Release(clientDrawingEffectPtr); } }
protected override void OnLoad(EventArgs e) { renderer = new TextRenderer(Width, Height); PointF position = PointF.Empty; renderer.Clear(Color.MidnightBlue); renderer.DrawString("The quick brown fox jumps over the lazy dog", serif, Brushes.White, position); position.Y += serif.Height; renderer.DrawString("The quick brown fox jumps over the lazy dog", sans, Brushes.White, position); position.Y += sans.Height; renderer.DrawString("The quick brown fox jumps over the lazy dog", mono, Brushes.White, position); position.Y += mono.Height; renderer.DrawString("The quick brown fox jumps over the lazy dog", mono, Brushes.White, position); position.Y += mono.Height; }
public void TextTable_LoadsAndRendersCorrectly_FromJson() { const Int32 TablePadding = 4; const Int32 TableOffset = 32; var spriteBatch = default(SpriteBatch); var spriteFont = default(SpriteFont); var textRenderer = default(TextRenderer); var table = default(TextTable<TextTableViewModel>); var tableLayout = default(TextTableLayout); var tableTexture = default(Texture2D); var result = GivenAnUltravioletApplication() .WithContent(content => { spriteBatch = SpriteBatch.Create(); spriteFont = content.Load<SpriteFont>("Fonts/SegoeUI"); textRenderer = new TextRenderer(); textRenderer.RegisterFont("header", content.Load<SpriteFont>("Fonts/Garamond")); textRenderer.RegisterFont("text", content.Load<SpriteFont>("Fonts/SegoeUI")); tableTexture = Texture2D.Create(1, 1); tableTexture.SetData(new[] { Color.White }); tableLayout = content.Load<TextTableLayout>("Tables/TestTextTableJson"); table = tableLayout.Create<TextTableViewModel>(textRenderer, spriteFont); }) .Render(uv => { uv.GetGraphics().Clear(Color.Magenta); spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend); table.PerformLayout(); spriteBatch.Draw(tableTexture, new RectangleF(TableOffset, TableOffset, table.ActualWidth + (TablePadding * 2), table.ActualHeight + (TablePadding * 2)), Color.Black * 0.75f); table.Draw(spriteBatch, Vector2.One * (TableOffset + TablePadding)); spriteBatch.End(); }); TheResultingImage(result). ShouldMatch(@"Resources/Expected/Graphics/Graphics2D/Text/TextTable_LoadsAndRendersCorrectly_FromJson.png"); }
public LoadingScreen(ContentManager globalContent, UIScreenService uiScreenService) : base("Content/UI/Screens/LoadingScreen", "LoadingScreen", globalContent) { Contract.Require(uiScreenService, "uiScreenService"); this.uiScreenService = uiScreenService; this.textRenderer = new TextRenderer(); this.blankTexture = GlobalContent.Load<Texture2D>(GlobalTextureID.Blank); this.font = GlobalContent.Load<SpriteFont>(GlobalFontID.SegoeUI); this.spinnerSprite = LocalContent.Load<Sprite>("Spinner"); this.loader = new AsynchronousContentLoader(); this.textRenderer.RegisterIcon("spinner", spinnerSprite[0]); UpdateMessage(String.Empty); }
public MenuComponent(Game game, SpriteBatch spriteBatch, TextRenderer textRenderer, Texture2D backgroundTexture, Texture2D highlightTexture, string[] menuItems) : base(game) { this.spriteBatch = spriteBatch; this.textRenderer = textRenderer; this.menuItems = menuItems; this.backgroundTexture = backgroundTexture; this.highlightTexture = highlightTexture; LinePadding = 5; MeasureMenu(); }
public static void ProcessFile(string filename) { string text = File.ReadAllText(filename); Lexer lexer = new Lexer(); if (languages.Count > 0) { foreach (var lang in languages) { if (IsFilename(lang)) lexer.ConfigureFromFile(lang); else lexer.Configure(lang); } } else if (filename.EndsWith(".rb")) lexer.Configure("Ruby"); else if (filename.EndsWith(".cs")) lexer.Configure("CSharp"); else if (filename.EndsWith(".js")) lexer.Configure("Javascript"); else if (filename.EndsWith(".py")) lexer.Configure("Python"); else if (filename.EndsWith(".cob")) lexer.Configure("Cobol"); else if (filename.EndsWith(".ms")) lexer.Configure("Mass"); if (styles.Count == 0) { WriteToConsole(text, lexer); return; } TextRenderer renderer = new TextRenderer(lexer); foreach (var t in styles) { if (IsFilename(t)) renderer.ConfigureFromFile(t); else renderer.Configure(t); } Console.Write(renderer.Render(text)); }
/// <summary> /// Create a text renderer. /// </summary> /// <param name="maxCharCount">Max char count to display for this label. Careful to set this value because greater <paramref name="maxCharCount"/> means more space ocupied in GPU nemory.</param> /// <param name="labelHeight">Label height(in pixels)</param> /// <param name="fontTexture">Use which font to render text?</param> /// <returns></returns> public static TextRenderer Create(int maxCharCount = 64, int labelHeight = 32, IFontTexture fontTexture = null) { if (fontTexture == null) { fontTexture = FontTexture.Default; }// FontResource.Default; } var shaderCodes = new ShaderCode[2]; shaderCodes[0] = new ShaderCode(ManifestResourceLoader.LoadTextFile( @"Resources.TextModel.vert"), ShaderType.VertexShader); shaderCodes[1] = new ShaderCode(ManifestResourceLoader.LoadTextFile( @"Resources.TextModel.frag"), ShaderType.FragmentShader); var map = new AttributeMap(); map.Add("position", TextModel.strPosition); map.Add("uv", TextModel.strUV); var model = new TextModel(maxCharCount); var renderer = new TextRenderer(model, shaderCodes, map); renderer.fontTexture = fontTexture; return renderer; }
/// <summary> /// Initializes a new instance of the <see cref="ScrollingTextBlock"/> class. /// </summary> /// <param name="textRenderer">The text renderer which will be used to draw the scrolling text block's text.</param> /// <param name="font">The sprite font which will be used to draw the scrolling text block's text.</param> /// <param name="text">The string which is displayed by the scrolling text block.</param> /// <param name="width">The width of the scrolling text block's layout area in pixels, /// or <see langword="null"/> to give the layout area an unconstrained width.</param> /// <param name="height">The height of the scrolling text block's layout area in pixels, /// or <see langword="null"/> to give the layout area an unconstrained height.</param> public ScrollingTextBlock(TextRenderer textRenderer, SpriteFont font, String text, Int32? width, Int32? height) { Contract.Require(textRenderer, nameof(textRenderer)); Contract.Require(font, nameof(font)); Contract.Require(text, nameof(text)); this.TextRenderer = textRenderer; this.Font = font; this.Width = width; this.Height = height; this.textParserTokens = new TextParserTokenStream(); this.textLayoutCommands = new TextLayoutCommandStream(); this.Text = text; this.TextRenderer.Parse(text, textParserTokens); this.TextRenderer.CalculateLayout(Text, textLayoutCommands, new TextLayoutSettings(Font, width, height, TextFlags.Standard)); Reset(); }
public void TextRenderer_CorrectlyCalculatesBoundingBoxOfFormattedText() { var spriteBatch = default(SpriteBatch); var spriteFont = default(SpriteFont); var textRenderer = default(TextRenderer); var blankTexture = default(Texture2D); var result = GivenAnUltravioletApplication() .WithContent(content => { spriteBatch = SpriteBatch.Create(); spriteFont = content.Load<SpriteFont>("Fonts/Garamond"); textRenderer = new TextRenderer(); blankTexture = Texture2D.Create(1, 1); blankTexture.SetData(new[] { Color.White }); }) .Render(uv => { const string text = "Lorem ipsum dolor sit amet,\n" + "|b|consectetur adipiscing elit.|b|\n" + "\n" + "|i|Pellentesque egestas luctus sapien|i|\n" + "|b||i|in malesuada.|i||b|\n" + "\n"; var window = uv.GetPlatform().Windows.GetPrimary(); var width = window.ClientSize.Width; var height = window.ClientSize.Height; uv.GetGraphics().Clear(Color.CornflowerBlue); spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend); var settings = new TextLayoutSettings(spriteFont, width, height, TextFlags.AlignMiddle | TextFlags.AlignCenter); var bounds = textRenderer.Draw(spriteBatch, text, Vector2.Zero, Color.White, settings); spriteBatch.Draw(blankTexture, bounds, Color.Red * 0.5f); spriteBatch.End(); }); TheResultingImage(result) .ShouldMatch(@"Resources\Expected\Graphics\Graphics2D\Text\TextRenderer_CorrectlyCalculatesBoundingBoxOfFormattedText.png"); }
/// <summary> /// Performs custom painting for a list item. /// </summary> /// <param name="e"></param> protected override void OnDrawItem(DrawItemEventArgs e) { base.OnDrawItem(e); if ((e.Index >= 0) && (e.Index < Items.Count)) { // get noteworthy states bool comboBoxEdit = (e.State & DrawItemState.ComboBoxEdit) == DrawItemState.ComboBoxEdit; bool selected = (e.State & DrawItemState.Selected) == DrawItemState.Selected; bool noAccelerator = (e.State & DrawItemState.NoAccelerator) == DrawItemState.NoAccelerator; bool disabled = (e.State & DrawItemState.Disabled) == DrawItemState.Disabled; bool focus = (e.State & DrawItemState.Focus) == DrawItemState.Focus; // determine grouping string groupText; bool isGroupStart = IsGroupStart(e.Index, out groupText) && !comboBoxEdit; bool hasGroup = (groupText != String.Empty) && !comboBoxEdit; // the item text will appear in a different colour, depending on its state Color textColor; if (disabled) { textColor = SystemColors.GrayText; } else if (!comboBoxEdit && selected) { textColor = SystemColors.HighlightText; } else { textColor = ForeColor; } // items will be indented if they belong to a group Rectangle itemBounds = Rectangle.FromLTRB( e.Bounds.X + (hasGroup ? 12 : 0), e.Bounds.Y + (isGroupStart ? (e.Bounds.Height / 2) : 0), e.Bounds.Right, e.Bounds.Bottom ); Rectangle groupBounds = new Rectangle( e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height / 2 ); if (isGroupStart && selected) { // ensure that the group header is never highlighted e.Graphics.FillRectangle(SystemBrushes.Highlight, e.Bounds); e.Graphics.FillRectangle(new SolidBrush(BackColor), groupBounds); } else if (disabled) { // disabled appearance e.Graphics.FillRectangle(Brushes.WhiteSmoke, e.Bounds); } else if (!comboBoxEdit) { // use the default background-painting logic e.DrawBackground(); } // render group header text if (isGroupStart) { TextRenderer.DrawText( e.Graphics, groupText, _groupFont, groupBounds, ForeColor, _textFormatFlags ); } // render item text TextRenderer.DrawText( e.Graphics, GetItemText(Items[e.Index]), Font, itemBounds, textColor, _textFormatFlags ); // paint the focus rectangle if required if (focus && !noAccelerator) { if (isGroupStart && selected) { // don't draw the focus rectangle around the group header ControlPaint.DrawFocusRectangle(e.Graphics, Rectangle.FromLTRB(groupBounds.X, itemBounds.Y, itemBounds.Right, itemBounds.Bottom)); } else { // use default focus rectangle painting logic e.DrawFocusRectangle(); } } } }
public void Initialize(Game1 game) { var skin = new Skin(game.GreyImageMap, game.GreyMap); var text = new TextRenderer(game.GreySpriteFont, Color.White); const int margin = 10; const int buttonHeight = 40; int i = -1; gui = new Gui(game, skin, text) { Widgets = new Widget[] { useToonButton = new ToggleButton(margin, margin + (buttonHeight * ++i), "Use Toon") { IsToggled = true }, drawOutlineButton = new ToggleButton(margin, margin + (buttonHeight * ++i), "Draw Outline") { IsToggled = true }, useXToon = new ToggleButton(margin, margin + (buttonHeight * ++i), "Use X-Toon") { IsToggled = false }, secondDimension = new ComboBox(margin + 100, margin + (buttonHeight * i), 150, "Second Dimension", CardinalDirection.South, new List<ComboBox.DropDownItem>() { new ComboBox.DropDownItem("Distance"), new ComboBox.DropDownItem("Angle") }), useTextureButton = new ToggleButton(margin, margin + (buttonHeight * ++i), "Use Textures") { IsToggled = true }, edgeWidth = new Slider(margin, margin + (buttonHeight * ++i), 150, delegate(Widget slider) { edgeWidthLabel.Value = "Edge Width = " + (((Slider)slider).Value * maxEdgeWidth); }) { Value = 1 / maxEdgeWidth }, edgeWidthLabel = new Label(margin, margin + (buttonHeight * ++i), "Edge Width = 1.0"), edgeIntensity = new Slider(margin, margin + (buttonHeight * ++i), 150, delegate(Widget slider) { edgeIntensityLabel.Value = "Edge Intensity = " + (((Slider)slider).Value * maxEdgeIntensity); }) { Value = 1 / maxEdgeIntensity }, edgeIntensityLabel = new Label(margin, margin + (buttonHeight * ++i), "Edge Intensity = 1.0"), detailAdjustment = new Slider(margin, margin + (buttonHeight * ++i), 150, delegate(Widget slider) { detailAdjustmentLabel.Value = "Detail Adjustment = " + (((Slider)slider).Value * maxDetail); }) { Value = 1 / maxDetail }, detailAdjustmentLabel = new Label(margin, margin + (buttonHeight * ++i), "Detail Adjustment = 1.0"), useLightDirections = new ToggleButton(margin, margin + (buttonHeight * ++i), "Use Light Directions"), lightAttentuation = new Slider(margin, margin + (buttonHeight * ++i), 150, delegate(Widget slider) { lightAttenuationLabel.Value = "Light attenuation = " + (((Slider)slider).Value * maxAttenuation); }) { Value = 1200 / maxAttenuation }, lightAttenuationLabel = new Label(margin, margin + (buttonHeight * ++i), "Light attentuation = 1200.0"), disableLighting = new ToggleButton(margin, margin + (buttonHeight * ++i), "Disable lighting") } }; }
public void Draw(object clientDrawingContext, TextRenderer renderer, float originX, float originY, bool isSideways, bool isRightToLeft, ComObject clientDrawingEffect) { }
protected override void OnPaint(PaintEventArgs e) { e.Graphics.SetClip(new Rectangle(margin, 0, Width - margin, Height)); double currentFrameX = 20 + margin + (currentFrame - frameLeft) * (Width - 40 - margin) / (frameRight - frameLeft); base.OnPaint(e); e.Graphics.DrawLine(pen2, new Point((int)currentFrameX, barHeight), new Point((int)currentFrameX, Height)); e.Graphics.DrawString("" + currentFrame, font, brush1, new Point((int)currentFrameX - TextRenderer.MeasureText("" + currentFrame, font).Width / 2, 0)); }
/// <summary>Override; see base.</summary> protected override void OnPaint(PaintEventArgs e) { Color initialColor = Enabled ? ForeColor : SystemColors.GrayText; if (_cachedRendering == null || _cachedRenderingWidth != ClientSize.Width || _cachedRenderingColor != initialColor) { _cachedRendering = new List <renderingInfo>(); _cachedRenderingWidth = ClientSize.Width; _cachedRenderingColor = initialColor; _specialLocations.Clear(); doPaintOrMeasure(e.Graphics, _parsed, Font, initialColor, _cachedRenderingWidth, _cachedRendering, _specialLocations); // If this control has focus and it has a link in it, focus the first link. (This triggers the LinkGotFocus event.) if (!_lastHadFocus) { _keyboardFocusOnLink = null; } else if (_keyboardFocusOnLink == null) { _keyboardFocusOnLink = _specialLocations.OfType <linkLocationInfo>().FirstOrDefault(); } checkForLinksAndTooltips(PointToClient(Control.MousePosition)); } foreach (var item in _cachedRendering) { if (item.Rectangle.Bottom < e.ClipRectangle.Top || item.Rectangle.Right < e.ClipRectangle.Left || item.Rectangle.Left > e.ClipRectangle.Right) { continue; } if (item.Rectangle.Top > e.ClipRectangle.Bottom) { break; } var font = item.State.Font; if ((item.State.Mnemonic && ShowKeyboardCues) || (_mouseOnLink != null && item.State.ActiveLocations.Contains(_mouseOnLink))) { font = new Font(font, font.Style | FontStyle.Underline); } TextRenderer.DrawText(e.Graphics, item.Text, font, item.Rectangle.Location, (_mouseIsDownOnLink && item.State.ActiveLocations.Contains(_mouseOnLink)) || (_spaceIsDownOnLink && item.State.ActiveLocations.Contains(_keyboardFocusOnLink)) ? LinkActiveColor : item.State.Color, TextFormatFlags.NoPadding | TextFormatFlags.NoPrefix); } if (_keyboardFocusOnLink != null) { if (!_specialLocations.Contains(_keyboardFocusOnLink)) { _keyboardFocusOnLinkPrivate = null; // set the private one so that no event is triggered } else { foreach (var rectangle in _keyboardFocusOnLink.Rectangles) { ControlPaint.DrawFocusRectangle(e.Graphics, rectangle); } } } }
protected override void OnPaint(PaintEventArgs e) { e.Graphics.Clear(Themes.Theme.WindowBackgroundColor); using (SolidBrush b = new SolidBrush(Themes.Theme.WindowBorderColor)) { Rectangle topRect = new Rectangle(0, 0, Width, borderWidth); e.Graphics.FillRectangle(b, topRect); } if (BorderStyle != MetroFormBorderStyle.None) { using (Pen pen = new Pen(Themes.Theme.WindowBorderColor)) { e.Graphics.DrawLines(pen, new[] { new Point(0, borderWidth), new Point(0, Height - 1), new Point(Width - 1, Height - 1), new Point(Width - 1, borderWidth) }); } } Rectangle titleBounds = new Rectangle(); if (DisplayHeader) { titleBounds = new Rectangle(borderWidth, borderWidth, ClientRectangle.Width - (2 * borderWidth), (int)Math.Ceiling(Font.SizeInPoints)); } if (backImage != null && backMaxSize != 0) { Image img = MetroImage.ResizeImage(backImage, new Rectangle(0, 0, backMaxSize, backMaxSize)); if (_imageinvert) { img = MetroImage.ResizeImage(backImage, new Rectangle(0, 0, backMaxSize, backMaxSize)); } int backImageX = 0, backImageY = 0; switch (backLocation) { case BackLocation.TopLeft: backImageX = borderWidth + backImagePadding.Left; backImageY = borderWidth + backImagePadding.Top; titleBounds.X += img.Width + backImageX + backImagePadding.Right; titleBounds.Y += backImageY; titleBounds.Width -= img.Width + backImagePadding.Left + backImagePadding.Right; titleBounds.Height = Math.Max(titleBounds.Height, img.Height); break; case BackLocation.TopRight: backImageX = -(backImagePadding.Right + img.Width + borderWidth); backImageY = borderWidth + backImagePadding.Top; titleBounds.X += backImageX - backImagePadding.Left; titleBounds.Y += backImageY; titleBounds.Width -= img.Width + backImagePadding.Left + backImagePadding.Right; titleBounds.Height = Math.Max(titleBounds.Height, img.Height); break; case BackLocation.BottomLeft: backImageX = borderWidth + backImagePadding.Left; backImageY = -(img.Height + backImagePadding.Bottom + borderWidth); break; case BackLocation.BottomRight: backImageX = -(backImagePadding.Right + img.Width + borderWidth); backImageY = -(img.Height + backImagePadding.Bottom + borderWidth); break; } e.Graphics.DrawImage(img, backImageX < 0 ? ClientRectangle.Right - backImageX : backImageX, backImageY < 0 ? ClientRectangle.Bottom - backImageY : backImageY); } if (DisplayHeader) { TextFormatFlags flags = TextFormatFlags.EndEllipsis | GetTextFormatFlags() | TextFormatFlags.VerticalCenter; TextRenderer.DrawText(e.Graphics, Text, Font, titleBounds, Themes.Theme.WindowTitleForegroundColor, flags); } if (Resizable && (SizeGripStyle == SizeGripStyle.Auto || SizeGripStyle == SizeGripStyle.Show)) { using (SolidBrush b = new SolidBrush(Themes.Theme.WindowResizeGripColor)) { Size resizeHandleSize = new Size(2, 2); e.Graphics.FillRectangles(b, new Rectangle[] { new Rectangle(new Point(ClientRectangle.Width - 6, ClientRectangle.Height - 6), resizeHandleSize), new Rectangle(new Point(ClientRectangle.Width - 10, ClientRectangle.Height - 10), resizeHandleSize), new Rectangle(new Point(ClientRectangle.Width - 10, ClientRectangle.Height - 6), resizeHandleSize), new Rectangle(new Point(ClientRectangle.Width - 6, ClientRectangle.Height - 10), resizeHandleSize), new Rectangle(new Point(ClientRectangle.Width - 14, ClientRectangle.Height - 6), resizeHandleSize), new Rectangle(new Point(ClientRectangle.Width - 6, ClientRectangle.Height - 14), resizeHandleSize) }); } } }
public override void DrawDayHeader(System.Drawing.Graphics g, System.Drawing.Rectangle rect, DateTime date) { if (g == null) { throw new ArgumentNullException("g"); } // Header background bool isToday = date.Date.Equals(DateTime.Now.Date); Rectangle rHeader = rect; rHeader.X++; if (VisualStyleRenderer.IsSupported) { bool hasTodayColor = Theme.HasAppColor(UITheme.AppColor.Today); var headerState = VisualStyleElement.Header.Item.Normal; if (isToday && !hasTodayColor) { headerState = VisualStyleElement.Header.Item.Hot; } var renderer = new VisualStyleRenderer(headerState); renderer.DrawBackground(g, rHeader); if (isToday && hasTodayColor) { rHeader.X--; using (var brush = new SolidBrush(Theme.GetAppDrawingColor(UITheme.AppColor.Today, 64))) g.FillRectangle(brush, rHeader); } } else // classic theme { rHeader.Y++; var headerBrush = (isToday ? SystemBrushes.ButtonHighlight : SystemBrushes.ButtonFace); g.FillRectangle(headerBrush, rHeader); ControlPaint.DrawBorder3D(g, rHeader, Border3DStyle.Raised); } // Header text g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; // Day of month TextFormatFlags flags = TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine; using (Font font = new Font("Tahoma", 9, FontStyle.Bold)) { if (DOWStyle == DOWNameStyle.None) { flags |= TextFormatFlags.HorizontalCenter; } string dayNum = date.ToString(" d"); TextRenderer.DrawText(g, dayNum, font, rect, SystemColors.WindowText, flags); if (DOWStyle == DOWNameStyle.Long) { int strWidth = TextRenderer.MeasureText(g, dayNum, font).Width; rect.Width -= strWidth; rect.X += strWidth; } } // Day of week if (DOWStyle != DOWNameStyle.None) { if (DOWStyle == DOWNameStyle.Long) { flags |= TextFormatFlags.HorizontalCenter; } else { flags |= TextFormatFlags.Right; } using (Font font = new Font("Tahoma", 8, FontStyle.Regular)) { string dayName; if (DOWStyle == DOWNameStyle.Long) { dayName = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetDayName(date.DayOfWeek); } else { dayName = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedDayName(date.DayOfWeek); } TextRenderer.DrawText(g, dayName, font, rect, SystemColors.WindowText, flags); } } }
protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); dynamic G = e.Graphics; var _with1 = G; StringFormat _StringF = new StringFormat { LineAlignment = StringAlignment.Center }; _with1.Clear(Color.FromArgb(31, 31, 31)); _with1.FillRectangle(new SolidBrush(_HeaderColor), new Rectangle(0, 0, Width, 5)); _with1.FillRectangle(new SolidBrush(Color.FromArgb(34, 34, 34)), new Rectangle(0, 5, Width, _HeaderSize)); _with1.DrawLine(new Pen(Color.FromArgb(38, 38, 38)), new Point(0, _HeaderSize + 5), new Point(Width, _HeaderSize + 5)); _with1.DrawLine(new Pen(Color.FromArgb(24, 24, 24)), new Point(0, _HeaderSize + 6), new Point(Width, _HeaderSize + 6)); _with1.DrawLine(Pens.Fuchsia, new Point(0, 0), new Point(0, 2)); _with1.DrawLine(Pens.Fuchsia, new Point(0, 0), new Point(2, 0)); _with1.DrawLine(Pens.Fuchsia, new Point(Width - 1, 0), new Point(Width - 1, 2)); _with1.DrawLine(Pens.Fuchsia, new Point(Width - 1, 0), new Point(Width - 3, 0)); if (_ControlsAlignment == ControlsAlign.Right) { if (_ShowClose == true) { _with1.DrawString("r", new Font("Marlett", 11), Brushes.White, new RectangleF(Width - 23, 5, 23, _HeaderSize + 3), _ControlsFormat); } if (_ShowMinimize == true) { if (_ShowMaximize == true) { if (_ShowClose == true) { G.DrawString("0", new Font("Marlett", 11), Brushes.White, new RectangleF(Width - 57, 5, 23, _HeaderSize + 3), _ControlsFormat); } else { G.DrawString("0", new Font("Marlett", 11), Brushes.White, new RectangleF(Width - 41, 5, 23, _HeaderSize + 3), _ControlsFormat); } } else { if (_ShowClose == true) { G.DrawString("0", new Font("Marlett", 11), Brushes.White, new RectangleF(Width - 41, 5, 23, _HeaderSize + 3), _ControlsFormat); } else { G.DrawString("0", new Font("Marlett", 11), Brushes.White, new RectangleF(Width - 23, 5, 23, _HeaderSize + 3), _ControlsFormat); } } } if (_ShowMaximize == true) { if (_ShowClose == true) { if (Parent.FindForm().WindowState == FormWindowState.Maximized) { _with1.DrawString("1", new Font("Marlett", 11), Brushes.White, new RectangleF(Width - 41, 5, 23, _HeaderSize + 3), _ControlsFormat); } else if (Parent.FindForm().WindowState == FormWindowState.Normal) { _with1.DrawString("2", new Font("Marlett", 11), Brushes.White, new RectangleF(Width - 41, 5, 23, _HeaderSize + 3), _ControlsFormat); } } else { if (Parent.FindForm().WindowState == FormWindowState.Maximized) { _with1.DrawString("1", new Font("Marlett", 11), Brushes.White, new RectangleF(Width - 23, 5, 23, _HeaderSize + 3), _ControlsFormat); } else if (Parent.FindForm().WindowState == FormWindowState.Normal) { _with1.DrawString("2", new Font("Marlett", 11), Brushes.White, new RectangleF(Width - 23, 5, 23, _HeaderSize + 3), _ControlsFormat); } } } } if (_ControlsAlignment == ControlsAlign.Left) { if (_ShowClose == true) { _with1.DrawString("r", new Font("Marlett", 11), Brushes.White, new RectangleF(5, 5, 23, _HeaderSize + 3), _ControlsFormat); } if (_ShowMinimize == true) { if (_ShowMaximize == true) { if (_ShowClose == true) { G.DrawString("0", new Font("Marlett", 11), Brushes.White, new RectangleF(41, 5, 23, _HeaderSize + 3), _ControlsFormat); } else { G.DrawString("0", new Font("Marlett", 11), Brushes.White, new RectangleF(23, 5, 23, _HeaderSize + 3), _ControlsFormat); } } else { if (_ShowClose == true) { G.DrawString("0", new Font("Marlett", 11), Brushes.White, new RectangleF(23, 5, 23, _HeaderSize + 3), _ControlsFormat); } else { G.DrawString("0", new Font("Marlett", 11), Brushes.White, new RectangleF(5, 5, 23, _HeaderSize + 3), _ControlsFormat); } } } if (_ShowMaximize == true) { if (_ShowClose == true) { if (Parent.FindForm().WindowState == FormWindowState.Maximized) { _with1.DrawString("1", new Font("Marlett", 11), Brushes.White, new RectangleF(23, 5, 23, _HeaderSize + 3), _ControlsFormat); } else if (Parent.FindForm().WindowState == FormWindowState.Normal) { _with1.DrawString("2", new Font("Marlett", 11), Brushes.White, new RectangleF(23, 5, 23, _HeaderSize + 3), _ControlsFormat); } } else { if (Parent.FindForm().WindowState == FormWindowState.Maximized) { _with1.DrawString("1", new Font("Marlett", 11), Brushes.White, new RectangleF(5, 5, 23, _HeaderSize + 3), _ControlsFormat); } else if (Parent.FindForm().WindowState == FormWindowState.Normal) { _with1.DrawString("2", new Font("Marlett", 11), Brushes.White, new RectangleF(5, 5, 23, _HeaderSize + 3), _ControlsFormat); } } } } switch (_TextAlignment) { case TextAlign.Center: _StringF.Alignment = StringAlignment.Center; _with1.DrawString(Text, new Font("Arial", 9), Brushes.White, new RectangleF(0, 5, Width, _HeaderSize), _StringF); break; case TextAlign.Left: _with1.DrawString(Text, new Font("Arial", 9), Brushes.White, new RectangleF(10, 5, Width, _HeaderSize), _StringF); break; case TextAlign.Right: int _TextLength = TextRenderer.MeasureText(Text, new Font("Arial", 9)).Width + 10; _with1.DrawString(Text, new Font("Arial", 9), Brushes.White, new RectangleF(Width - _TextLength, 5, Width, _HeaderSize), _StringF); break; } }
protected override void OnPaint(PaintEventArgs pevent) { base.OnPaint(pevent); if (!showSplit) { return; } Graphics g = pevent.Graphics; Rectangle bounds = this.ClientRectangle; // draw the button background as according to the current state. if (State != PushButtonState.Pressed && IsDefault && !Application.RenderWithVisualStyles) { Rectangle backgroundBounds = bounds; backgroundBounds.Inflate(-1, -1); ButtonRenderer.DrawButton(g, backgroundBounds, State); // button renderer doesnt draw the black frame when themes are off =( g.DrawRectangle(SystemPens.WindowFrame, 0, 0, bounds.Width - 1, bounds.Height - 1); } else { ButtonRenderer.DrawButton(g, bounds, State); } // calculate the current dropdown rectangle. dropDownRectangle = new Rectangle(bounds.Right - PushButtonWidth - 1, BorderSize, PushButtonWidth, bounds.Height - BorderSize * 2); int internalBorder = BorderSize; Rectangle focusRect = new Rectangle(internalBorder, internalBorder, bounds.Width - dropDownRectangle.Width - internalBorder, // bounds.Height - ( internalBorder * 2 ) ); bounds.Height - (internalBorder * 2) - 1); // [xiperware] shift label up 1px // bool drawSplitLine = (State == PushButtonState.Hot || State == PushButtonState.Pressed || !Application.RenderWithVisualStyles); bool drawSplitLine = true; // [xiperware] always draw split line if (RightToLeft == RightToLeft.Yes) { dropDownRectangle.X = bounds.Left + 1; focusRect.X = dropDownRectangle.Right; if (drawSplitLine) { // draw two lines at the edge of the dropdown button g.DrawLine(SystemPens.ButtonShadow, bounds.Left + PushButtonWidth, BorderSize, bounds.Left + PushButtonWidth, bounds.Bottom - BorderSize); g.DrawLine(SystemPens.ButtonFace, bounds.Left + PushButtonWidth + 1, BorderSize, bounds.Left + PushButtonWidth + 1, bounds.Bottom - BorderSize); } } else { if (drawSplitLine) { // draw two lines at the edge of the dropdown button g.DrawLine(SystemPens.ButtonShadow, bounds.Right - PushButtonWidth, BorderSize, bounds.Right - PushButtonWidth, bounds.Bottom - BorderSize - 1); // [xiperware] g.DrawLine(SystemPens.ButtonFace, bounds.Right - PushButtonWidth - 1, BorderSize, bounds.Right - PushButtonWidth - 1, bounds.Bottom - BorderSize - 1); // g.DrawLine( SystemPens.ButtonShadow, bounds.Right - PushButtonWidth, BorderSize, bounds.Right - PushButtonWidth, bounds.Bottom - BorderSize ); // g.DrawLine( SystemPens.ButtonFace, bounds.Right - PushButtonWidth - 1, BorderSize, bounds.Right - PushButtonWidth - 1, bounds.Bottom - BorderSize ); } } // Draw an arrow in the correct location PaintArrow(g, dropDownRectangle); // Figure out how to draw the text TextFormatFlags formatFlags = TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter; // If we dont' use mnemonic, set formatFlag to NoPrefix as this will show ampersand. if (!UseMnemonic) { formatFlags = formatFlags | TextFormatFlags.NoPrefix; } else if (!ShowKeyboardCues) { formatFlags = formatFlags | TextFormatFlags.HidePrefix; } if (!string.IsNullOrEmpty(this.Text)) { TextRenderer.DrawText(g, Text, Font, focusRect, SystemColors.ControlText, formatFlags); } // draw the focus rectangle. /* [xiperware] * if( State != PushButtonState.Pressed && Focused ) * { * ControlPaint.DrawFocusRectangle( g, focusRect ); * } */ }
/// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.splitterControl1 = new Syncfusion.Windows.Forms.SplitterControl(); this.gridControl1 = new Syncfusion.Windows.Forms.Grid.GridControl(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.comboBox1 = new System.Windows.Forms.ComboBox(); this.comboBox2 = new System.Windows.Forms.ComboBox(); this.comboBox3 = new System.Windows.Forms.ComboBox(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.panel1 = new System.Windows.Forms.Panel(); this.splitterControl1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.gridControl1)).BeginInit(); this.SuspendLayout(); // // splitterControl1 // this.splitterControl1.Dock = DockStyle.Fill; this.splitterControl1.BeforeTouchSize = new System.Drawing.Size(699, 404); this.splitterControl1.Controls.Add(this.gridControl1); this.splitterControl1.Location = new System.Drawing.Point(13, 13); this.splitterControl1.Name = "splitterControl1"; this.splitterControl1.Size = new System.Drawing.Size(699, 404); this.splitterControl1.TabIndex = 0; this.splitterControl1.Text = "splitterControl1"; this.splitterControl1.ShowToolTips = true; this.splitterControl1.HSplitPos = 50; this.splitterControl1.VSplitPos = 50; this.splitterControl1.Style = Syncfusion.Windows.Forms.Appearance.Metro; this.splitterControl1.SplitBars = DynamicSplitBars.Both; // // gridControl1 // this.gridControl1.DpiAware = true; this.gridControl1.Location = new System.Drawing.Point(12, 12); this.gridControl1.Name = "gridControl1"; this.gridControl1.Size = new System.Drawing.Size(699, 433); this.gridControl1.SmartSizeBox = false; this.gridControl1.Text = "gridControl1"; this.gridControl1.UseRightToLeftCompatibleTextBox = true; // // panel1 // this.panel1.Dock = DockStyle.Right; this.panel1.Location = new System.Drawing.Point(725, 21); this.panel1.Size = new System.Drawing.Size(300, 200); this.panel1.Controls.Add(this.groupBox1); // // groupBox1 // this.groupBox1.Controls.Add(this.label3); this.groupBox1.Controls.Add(this.label2); this.groupBox1.Controls.Add(this.label1); this.groupBox1.Controls.Add(this.comboBox1); this.groupBox1.Controls.Add(this.comboBox3); this.groupBox1.Controls.Add(this.comboBox2); this.groupBox1.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.groupBox1.Location = new System.Drawing.Point(15, 0); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(210, 160); this.groupBox1.TabStop = false; this.groupBox1.Text = "Settings"; this.groupBox1.Anchor = AnchorStyles.Top | AnchorStyles.Left; this.groupBox1.AutoSize = true; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.Location = new System.Drawing.Point(6, 111); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(78, 15); this.label3.TabIndex = 5; this.label3.Text = "Splitter Type"; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(6, 70); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(78, 15); this.label2.TabIndex = 5; this.label2.Text = "Scrollbar Style"; // //label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(6, 32); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(70, 15); this.label1.TabIndex = 4; this.label1.Text = "Show Scrollbar"; System.Drawing.Size textSize = TextRenderer.MeasureText("Office2010", this.comboBox3.Font); // // comboBox1 // this.comboBox1.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.comboBox1.FormattingEnabled = true; this.comboBox1.Items.AddRange(new object[] { "None", "Column", "Row", "Both" }); this.comboBox1.Location = new System.Drawing.Point(label1.Location.X + label1.Size.Width + 5, 110); this.comboBox1.SelectedItem = "Both"; this.comboBox1.Name = "SplitterBar Behavior"; this.comboBox1.Size = new System.Drawing.Size(textSize.Width + 30, textSize.Height); this.comboBox1.DropDownStyle = ComboBoxStyle.DropDownList; this.comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged; // // comboBox3 // this.comboBox3.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.comboBox3.FormattingEnabled = true; this.comboBox3.Items.AddRange(new object[] { "None", "Metro", "Office2007", "Office2010" }); this.comboBox3.Location = new System.Drawing.Point(label1.Location.X + label1.Size.Width + 5, 70); this.comboBox3.SelectedItem = "Metro"; this.comboBox3.Name = "Scrollbar Styles"; this.comboBox3.Size = new System.Drawing.Size(textSize.Width + 30, textSize.Height); this.comboBox3.DropDownStyle = ComboBoxStyle.DropDownList; this.comboBox3.BackColor = System.Drawing.Color.White; this.comboBox3.SelectedIndexChanged += comboBox3_SelectedIndexChanged; // // comboBox2 // this.comboBox2.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.comboBox2.FormattingEnabled = true; this.comboBox2.Items.AddRange(new object[] { "None", "Horizontal", "Vertical", "Both" }); this.comboBox2.Location = new System.Drawing.Point(label1.Location.X + label1.Size.Width + 5, 30); this.comboBox2.SelectedItem = "Both"; this.comboBox2.Name = "Enablescrollbar"; this.comboBox2.Size = new System.Drawing.Size(textSize.Width + 30, textSize.Height); this.comboBox2.DropDownStyle = ComboBoxStyle.DropDownList; this.comboBox2.SelectedIndexChanged += ComboBox2_SelectedIndexChanged; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(940, 420); this.splitterControl1.Controls.Add(gridControl1); this.Controls.Add(this.splitterControl1); this.Controls.Add(this.panel1); this.MinimumSize = new System.Drawing.Size(500, 300); this.Name = "Form1"; this.Text = "Split Pane"; this.splitterControl1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.gridControl1)).EndInit(); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.ResumeLayout(false); }
public static float GetTextWidthInPixels(string text, Font font) { var size = TextRenderer.MeasureText(text, font); return(size.Width); }
private Size doPaintOrMeasure(Graphics g, EggsNode node, Font initialFont, Color initialForeColor, int constrainingWidth, List <renderingInfo> renderings = null, List <locationInfo> locations = null) { var glyphOverhang = TextRenderer.MeasureText(g, "Wg", initialFont, _dummySize) - TextRenderer.MeasureText(g, "Wg", initialFont, _dummySize, TextFormatFlags.NoPadding); int x = glyphOverhang.Width / 2, y = glyphOverhang.Height / 2; int wrapWidth = WordWrap ? Math.Max(1, constrainingWidth - glyphOverhang.Width) : int.MaxValue; int hangingIndent = _hangingIndent * (_hangingIndentUnit == IndentUnit.Spaces ? measure(initialFont, " ", g).Width : 1); bool atBeginningOfLine = false; // STEP 1: Run the word-wrapping as if TextAlign were TopLeft int actualWidth = EggsML.WordWrap(node, new renderState(initialFont, initialForeColor), wrapWidth, (state, text) => measure(state.Font, text, g).Width, (state, text, width) => { if (state.Mnemonic && !string.IsNullOrWhiteSpace(text)) { state.ActiveLocations.OfType <linkLocationInfo>().FirstOrDefault().NullOr(link => { link.Mnemonic = char.ToLowerInvariant(text.Trim()[0]); return(link); }); } if (renderings != null && !string.IsNullOrEmpty(text)) { renderingInfo info; if (!atBeginningOfLine && renderings.Count > 0 && (info = renderings[renderings.Count - 1]).State == state) { info.Text += text; var rect = info.Rectangle; rect.Width += width; info.Rectangle = rect; } else { info = new renderingInfo(text, new Rectangle(x, y, width, measure(state.Font, " ", g).Height), state); renderings.Add(info); } foreach (var location in state.ActiveLocations) { if (location.Rectangles.Count == 0 || location.Rectangles[location.Rectangles.Count - 1].Y != info.Rectangle.Y) { location.Rectangles.Add(info.Rectangle); } else { var rect = location.Rectangles[location.Rectangles.Count - 1]; rect.Width += width; location.Rectangles[location.Rectangles.Count - 1] = rect; } } } atBeginningOfLine = false; x += width; }, (state, newParagraph, indent) => { atBeginningOfLine = true; var sh = measure(state.Font, " ", g).Height; y += sh; if (newParagraph && _paragraphSpacing > 0) { y += (int)(_paragraphSpacing * sh); } var newIndent = state.BlockIndent + indent; if (!newParagraph) { newIndent += hangingIndent; } x = newIndent + glyphOverhang.Width / 2; return(newIndent); }, (state, tag, parameter) => { var font = state.Font; switch (tag) { // ITALICS case '/': return(state.ChangeFont(new Font(font, font.Style | FontStyle.Italic)), 0);
public void TextRenderer_CanRenderStyledStrings() { var spriteBatch = default(SpriteBatch); var spriteFont = default(SpriteFont); var textRenderer = default(TextRenderer); var result = GivenAnUltravioletApplication() .WithContent(content => { spriteBatch = SpriteBatch.Create(); spriteFont = content.Load<SpriteFont>("Fonts/Garamond"); textRenderer = new TextRenderer(); }) .Render(uv => { spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend); var settings = new TextLayoutSettings(spriteFont, null, null, TextFlags.Standard); textRenderer.Draw(spriteBatch, "This string is regular\n" + "|b|This string is bold|b|\n" + "|i|This string is italic|i|\n" + "|b||i|This string is bold italic|i||b|", Vector2.Zero, Color.White, settings); spriteBatch.End(); }); TheResultingImage(result) .ShouldMatch(@"Resources\Expected\Graphics\Graphics2D\Text\TextRenderer_CanRenderStyledStrings.png"); }
/// <summary> /// Draws text using the specified client drawing context. /// </summary> /// <remarks> /// To draw text with this method, a textLayout object needs to be created by the application using <see cref="SharpDX.DirectWrite.Factory.CreateTextLayout"/>. After the textLayout object is obtained, the application calls the IDWriteTextLayout::Draw method to draw the text, decorations, and inline objects. The actual drawing is done through the callback interface passed in as the textRenderer argument; there, the corresponding DrawGlyphRun API is called. /// </remarks> /// <param name="clientDrawingContext">An application-defined drawing context. </param> /// <param name="renderer">Pointer to the set of callback functions used to draw parts of a text string.</param> /// <param name="originX">The x-coordinate of the layout's left side.</param> /// <param name="originY">The y-coordinate of the layout's top side.</param> /// <returns>If the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> /// <unmanaged>HRESULT Draw([None] void* clientDrawingContext,[None] IDWriteTextRenderer* renderer,[None] FLOAT originX,[None] FLOAT originY)</unmanaged> public void Draw(object clientDrawingContext, TextRenderer renderer, float originX, float originY) { var handle = GCHandle.Alloc(clientDrawingContext); try { this.Draw_(GCHandle.ToIntPtr(handle), TextRendererShadow.ToIntPtr(renderer), originX, originY); } finally { if (handle.IsAllocated) handle.Free(); } }
public void TextRenderer_CorrectlyAlignsKernedTextAcrossTokenBoundaries() { var spriteBatch = default(SpriteBatch); var spriteFont = default(SpriteFont); var textRenderer = default(TextRenderer); var result = GivenAnUltravioletApplication() .WithContent(content => { spriteBatch = SpriteBatch.Create(); spriteFont = content.Load<SpriteFont>("Fonts/Garamond"); textRenderer = new TextRenderer(); }) .Render(uv => { const string text = "||c:AARRGGBB| - Changes the color of text.\n" + "|c:FFFF0000|red|c| |c:FFFF8000|orange|c| |c:FFFFFF00|yellow|c| |c:FF00FF00|green|c| |c:FF0000FF|blue|c| |c:FF6F00FF|indigo|c| |c:FFFF00FF|magenta|c|"; var window = uv.GetPlatform().Windows.GetPrimary(); var width = window.ClientSize.Width; var height = window.ClientSize.Height; spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend); var settings = new TextLayoutSettings(spriteFont, width, height, TextFlags.AlignMiddle | TextFlags.AlignCenter); textRenderer.Draw(spriteBatch, text, Vector2.Zero, Color.White, settings); spriteBatch.End(); }); TheResultingImage(result) .ShouldMatch(@"Resources\Expected\Graphics\Graphics2D\Text\TextRenderer_CorrectlyAlignsKernedTextAcrossTokenBoundaries.png"); }
public TableView(ShipListTable Owner) { SetStyle(ControlStyles.DoubleBuffer | ControlStyles.OptimizedDoubleBuffer, true); this.Owner = Owner; this.Resize += (s, e) => this.RequestUpdate(); this.Paint += (s, e) => { var g = e.Graphics; var Width = this.Width - this.Padding.Left - this.Padding.Right; var Height = this.Height - this.Padding.Top - this.Padding.Bottom; g.Clear(this.BackColor); #region Filtering var Ships = homeport?.Organization?.Ships.Select(_ => _.Value); if (Ships != null) { if (ShipTypes != null) { Ships = Ships.Where(_ => this.ShipTypes.Contains(_.Info.ShipType.Id)); } Ships = Ships.Where(_ => (_.Level >= this.LevelFrom) && (_.Level <= this.LevelTo) ); if (this.ExceptExpedition) { Ships = Ships.Where(_ => (_.FleetId == -1) || ((!homeport?.Organization?.Fleets[_.FleetId]?.Expedition?.IsInExecution) ?? false) ); } if (this.LockFilter == FilterValues.Yes) { Ships = Ships.Where(_ => _.IsLocked); } else if (this.LockFilter == FilterValues.No) { Ships = Ships.Where(_ => !_.IsLocked); } if (this.SpeedFilter == FilterValues.SuperFast) { Ships = Ships.Where(_ => _.Info.Speed == ShipSpeed.SuperFast); } else if (this.SpeedFilter == FilterValues.FastPlus) { Ships = Ships.Where(_ => _.Info.Speed == ShipSpeed.FastPlus); } else if (this.SpeedFilter == FilterValues.Fast) { Ships = Ships.Where(_ => _.Info.Speed == ShipSpeed.Fast); } else if (this.SpeedFilter == FilterValues.Slow) { Ships = Ships.Where(_ => _.Info.Speed == ShipSpeed.Slow); } if (this.PowerupFilter == FilterValues.End) { Ships = Ships.Where(_ => _.IsMaxModernized); } else if (this.PowerupFilter == FilterValues.NotEnd) { Ships = Ships.Where(_ => !_.IsMaxModernized); } } Ships = Ships?.OrderByDescending(_ => _.Exp); #endregion Font font7 = new Font(this.Font.FontFamily, 7); int widthLevelLv = TextRenderer.MeasureText("Lv.", font7).Width - 4; int widthLevelNext = TextRenderer.MeasureText("Next:", font7).Width - 3; int widthLevelInfo = widthLevelLv + widthLevelNext + 6; int widthPowerupMax = TextRenderer.MeasureText("MAX", font7).Width - 3; #region Cell Size Calculate ColumnSizes[1] = Ships?.Count() > 0 ? (Ships?.Max(_ => TextRenderer.MeasureText(_.Id.ToString(), this.Font).Width) ?? 0) : 0; ColumnSizes[2] = Ships?.Count() > 0 ? (Ships?.Max(_ => TextRenderer.MeasureText(_.Info.ShipType.Name, this.Font).Width) ?? 0) : 0; ColumnSizes[3] = Ships?.Count() > 0 ? (Ships?.Max(_ => TextRenderer.MeasureText(_.Info.Name, this.Font).Width) ?? 0) : 0; ColumnSizes[4] = Ships?.Count() > 0 ? (Ships?.Max(_ => TextRenderer.MeasureText(_.Level.ToString(), this.Font).Width + TextRenderer.MeasureText(_.ExpForNextLevel.ToString(), font7).Width + widthLevelInfo ) ?? 0) : 0; ColumnSizes[8] = Ships?.Count() > 0 ? (Ships?.Max(_ => TextRenderer.MeasureText(_.Firepower.Current.ToString(), this.Font).Width + widthPowerupMax ) ?? 0) : 0; ColumnSizes[9] = Ships?.Count() > 0 ? (Ships?.Max(_ => TextRenderer.MeasureText(_.Torpedo.Current.ToString(), this.Font).Width + widthPowerupMax ) ?? 0) : 0; ColumnSizes[10] = Ships?.Count() > 0 ? (Ships?.Max(_ => TextRenderer.MeasureText(_.YasenFp.Current.ToString(), this.Font).Width + widthPowerupMax ) ?? 0) : 0; ColumnSizes[11] = Ships?.Count() > 0 ? (Ships?.Max(_ => TextRenderer.MeasureText(_.Armor.Current.ToString(), this.Font).Width + widthPowerupMax ) ?? 0) : 0; ColumnSizes[12] = Ships?.Count() > 0 ? (Ships?.Max(_ => TextRenderer.MeasureText(_.AA.Current.ToString(), this.Font).Width + widthPowerupMax ) ?? 0) : 0; ColumnSizes[13] = Ships?.Count() > 0 ? (Ships?.Max(_ => TextRenderer.MeasureText(_.ASW.Current.ToString(), this.Font).Width + widthPowerupMax ) ?? 0) : 0; ColumnSizes[14] = Ships?.Count() > 0 ? (Ships?.Max(_ => TextRenderer.MeasureText(_.Luck.Current.ToString(), this.Font).Width + widthPowerupMax ) ?? 0) : 0; ColumnSizes[0] = Math.Max( TextRenderer.MeasureText(Ships?.Count().ToString(), this.Font).Width, 16 ) + 8; ColumnSizes[1] = Math.Max(ColumnSizes[1], TextRenderer.MeasureText(Headers[1], this.Font).Width) + 8; ColumnSizes[2] = Math.Max(ColumnSizes[2], TextRenderer.MeasureText(Headers[2], this.Font).Width) + 8; ColumnSizes[3] = Math.Max(ColumnSizes[3], TextRenderer.MeasureText(Headers[3], this.Font).Width) + 8; ColumnSizes[4] = Math.Max(ColumnSizes[4], TextRenderer.MeasureText(Headers[4], this.Font).Width) + 8; ColumnSizes[5] = TextRenderer.MeasureText(Headers[5], this.Font).Width + 8; ColumnSizes[6] = TextRenderer.MeasureText(Headers[6], this.Font).Width + 8; ColumnSizes[7] = TextRenderer.MeasureText(Headers[7], this.Font).Width + 8; ColumnSizes[8] = Math.Max(ColumnSizes[8], TextRenderer.MeasureText(Headers[8], this.Font).Width) + 8; ColumnSizes[9] = Math.Max(ColumnSizes[9], TextRenderer.MeasureText(Headers[9], this.Font).Width) + 8; ColumnSizes[10] = Math.Max(ColumnSizes[10], TextRenderer.MeasureText(Headers[10], this.Font).Width) + 8; ColumnSizes[11] = Math.Max(ColumnSizes[11], TextRenderer.MeasureText(Headers[11], this.Font).Width) + 8; ColumnSizes[12] = Math.Max(ColumnSizes[12], TextRenderer.MeasureText(Headers[12], this.Font).Width) + 8; ColumnSizes[13] = Math.Max(ColumnSizes[13], TextRenderer.MeasureText(Headers[13], this.Font).Width) + 8; ColumnSizes[14] = Math.Max(ColumnSizes[14], TextRenderer.MeasureText(Headers[14], this.Font).Width) + 8; ColumnSizes[15] = TextRenderer.MeasureText(Headers[15], this.Font).Width + 8; ColumnSizes[16] = TextRenderer.MeasureText(Headers[16], this.Font).Width + 8; ColumnSizes[17] = Math.Max( TextRenderer.MeasureText("00:00:00", this.Font).Width, TextRenderer.MeasureText(Headers[17], this.Font).Width ) + 8; #endregion int x, y = 0; using (Pen p = new Pen(Color.FromArgb(83, 83, 83), 1.0f)) { #region Data Rendering if (Ships != null) { Color colorWhite = Color.White; Color colorDarkGray = Color.FromArgb(0x20, 0x90, 0x90, 0x90); Color colorGray = Color.FromArgb(0x40, 0xC4, 0xC4, 0xC4); int idx = 0; y = 0; foreach (var ship in Ships) { int widthValue; x = 0; y -= 2; if (idx % 2 == 1) { using (SolidBrush b = new SolidBrush(Color.FromArgb(0x18, 0x90, 0x90, 0x90))) g.FillRectangle(b, new Rectangle(0, y, Width, RowSize)); } #region Index TextRenderer.DrawText( g, (idx + 1).ToString(), this.Font, new Rectangle(x + 3, y, ColumnSizes[0] - 8, RowSize), colorDarkGray, TextFormatFlags.VerticalCenter | TextFormatFlags.Left ); x += ColumnSizes[0]; #endregion #region Ship ID TextRenderer.DrawText( g, ship.Id.ToString(), this.Font, new Rectangle(x + 3, y, ColumnSizes[1] - 8, RowSize), colorGray, TextFormatFlags.VerticalCenter | TextFormatFlags.Left ); x += ColumnSizes[1]; #endregion #region Ship Type Name TextRenderer.DrawText( g, ship.Info.ShipType.Name, this.Font, new Rectangle(x + 3, y, ColumnSizes[2] - 8, RowSize), colorGray, TextFormatFlags.VerticalCenter | TextFormatFlags.Left ); x += ColumnSizes[2]; #endregion #region Ship Name TextRenderer.DrawText( g, ship.Info.Name, this.Font, new Rectangle(x + 3, y, ColumnSizes[3] - 8, RowSize), colorWhite, TextFormatFlags.VerticalCenter | TextFormatFlags.Left ); x += ColumnSizes[3]; #endregion #region Ship Level widthValue = TextRenderer.MeasureText(ship.Level.ToString(), this.Font).Width; TextRenderer.DrawText( g, "Lv.", font7, new Rectangle(x + 3, y, ColumnSizes[4] - 8, RowSize - 3), colorGray, TextFormatFlags.Bottom | TextFormatFlags.Left ); TextRenderer.DrawText( g, ship.Level.ToString(), this.Font, new Rectangle(x + widthLevelLv + 2 + 3, y, ColumnSizes[4] - 8 - widthLevelLv - 2, RowSize - 3), colorWhite, TextFormatFlags.Bottom | TextFormatFlags.Left ); TextRenderer.DrawText( g, "Next:", font7, new Rectangle( x + widthLevelLv + 2 + widthValue + 2 + 3, y, ColumnSizes[4] - 8 - widthLevelLv - 2 - widthValue - 4, RowSize - 3 ), colorGray, TextFormatFlags.Bottom | TextFormatFlags.Left ); TextRenderer.DrawText( g, ship.ExpForNextLevel.ToString(), font7, new Rectangle( x + widthLevelLv + 2 + widthValue + 2 + widthLevelNext + 3, y, ColumnSizes[4] - 8 - widthLevelLv - 2 - widthValue - 4 - widthLevelNext - 3, RowSize - 3 ), colorGray, TextFormatFlags.Bottom | TextFormatFlags.Left ); x += ColumnSizes[4]; #endregion #region Ship Remodel if (ship.RemodelLevel == -1) { using (SolidBrush b = new SolidBrush(Color.FromArgb(0x38, 0x4C, 0xD1))) g.FillRectangle(b, new Rectangle(x, y, ColumnSizes[5], RowSize)); TextRenderer.DrawText( g, "개장가능", this.Font, new Rectangle(x + 3, y, ColumnSizes[5] - 8, RowSize), colorWhite, TextFormatFlags.VerticalCenter | TextFormatFlags.Left ); } else if (ship.RemodelLevel > 0) { TextRenderer.DrawText( g, "Lv.", font7, new Rectangle(x + 3, y, ColumnSizes[5] - 8, RowSize - 3), colorGray, TextFormatFlags.Bottom | TextFormatFlags.Left ); TextRenderer.DrawText( g, ship.RemodelLevel.ToString(), this.Font, new Rectangle(x + widthLevelLv + 3, y, ColumnSizes[5] - 8, RowSize), colorWhite, TextFormatFlags.VerticalCenter | TextFormatFlags.Left ); } x += ColumnSizes[5]; #endregion #region Ship Condition using (SolidBrush b = new SolidBrush(GetCondColor(ship.ConditionType))) g.FillRectangle(b, new Rectangle(x + 6, y + 7, 9, 9)); TextRenderer.DrawText( g, ship.Condition.ToString(), this.Font, new Rectangle(x + 14 + 3, y, ColumnSizes[6] - 8, RowSize), colorWhite, TextFormatFlags.VerticalCenter | TextFormatFlags.Left ); x += ColumnSizes[6]; #endregion #region Ship Max HP TextRenderer.DrawText( g, ship.HP.Maximum.ToString(), this.Font, new Rectangle(x + 3, y, ColumnSizes[7] - 8, RowSize), colorWhite, TextFormatFlags.VerticalCenter | TextFormatFlags.Left ); x += ColumnSizes[7]; #endregion #region Firepower widthValue = TextRenderer.MeasureText(ship.Firepower.Current.ToString(), this.Font).Width - 4; if (ship.Firepower.IsMax) { using (SolidBrush b = new SolidBrush(Color.FromArgb(0x7F, 0xB1, 0x3B, 0x2A))) g.FillRectangle(b, new Rectangle(x, y, ColumnSizes[8], RowSize)); } TextRenderer.DrawText( g, ship.Firepower.Current.ToString(), this.Font, new Rectangle(x + 3, y, ColumnSizes[8] - 8, RowSize), colorWhite, TextFormatFlags.VerticalCenter | TextFormatFlags.Left ); if (ship.Firepower.IsMax) { TextRenderer.DrawText( g, "MAX", font7, new Rectangle(x + widthValue + 2 + 3, y, ColumnSizes[8] - 8, RowSize - 3), colorGray, TextFormatFlags.Bottom | TextFormatFlags.Left ); } else { TextRenderer.DrawText( g, "+" + ship.Firepower.Shortfall.ToString(), font7, new Rectangle(x + widthValue + 3, y, ColumnSizes[8] - 8, RowSize - 3), colorGray, TextFormatFlags.Bottom | TextFormatFlags.Left ); } x += ColumnSizes[8]; #endregion #region Torpedo widthValue = TextRenderer.MeasureText(ship.Torpedo.Current.ToString(), this.Font).Width - 4; if (ship.Torpedo.IsMax) { using (SolidBrush b = new SolidBrush(Color.FromArgb(0x7F, 0x29, 0x70, 0xAB))) g.FillRectangle(b, new Rectangle(x, y, ColumnSizes[9], RowSize)); } TextRenderer.DrawText( g, ship.Torpedo.Current.ToString(), this.Font, new Rectangle(x + 3, y, ColumnSizes[9] - 8, RowSize), colorWhite, TextFormatFlags.VerticalCenter | TextFormatFlags.Left ); if (ship.Torpedo.IsMax) { TextRenderer.DrawText( g, "MAX", font7, new Rectangle(x + widthValue + 2 + 3, y, ColumnSizes[9] - 8, RowSize - 3), colorGray, TextFormatFlags.Bottom | TextFormatFlags.Left ); } else { TextRenderer.DrawText( g, "+" + ship.Torpedo.Shortfall.ToString(), font7, new Rectangle(x + widthValue + 3, y, ColumnSizes[9] - 8, RowSize - 3), colorGray, TextFormatFlags.Bottom | TextFormatFlags.Left ); } x += ColumnSizes[9]; #endregion #region Firepower + Torpedo widthValue = TextRenderer.MeasureText(ship.YasenFp.Current.ToString(), this.Font).Width - 4; if (ship.YasenFp.IsMax) { using (SolidBrush b = new SolidBrush(Color.FromArgb(0x66, 0x33, 0x99))) g.FillRectangle(b, new Rectangle(x, y, ColumnSizes[10], RowSize)); } TextRenderer.DrawText( g, ship.YasenFp.Current.ToString(), this.Font, new Rectangle(x + 3, y, ColumnSizes[10] - 8, RowSize), colorWhite, TextFormatFlags.VerticalCenter | TextFormatFlags.Left ); if (ship.YasenFp.IsMax) { TextRenderer.DrawText( g, "MAX", font7, new Rectangle(x + widthValue + 2 + 3, y, ColumnSizes[10] - 8, RowSize - 3), colorGray, TextFormatFlags.Bottom | TextFormatFlags.Left ); } else { TextRenderer.DrawText( g, "+" + ship.YasenFp.Shortfall.ToString(), font7, new Rectangle(x + widthValue + 3, y, ColumnSizes[10] - 8, RowSize - 3), colorGray, TextFormatFlags.Bottom | TextFormatFlags.Left ); } x += ColumnSizes[10]; #endregion #region Armor widthValue = TextRenderer.MeasureText(ship.Armor.Current.ToString(), this.Font).Width - 4; if (ship.Armor.IsMax) { using (SolidBrush b = new SolidBrush(Color.FromArgb(0x7F, 0xD8, 0x98, 0x1A))) g.FillRectangle(b, new Rectangle(x, y, ColumnSizes[11], RowSize)); } TextRenderer.DrawText( g, ship.Armor.Current.ToString(), this.Font, new Rectangle(x + 3, y, ColumnSizes[11] - 8, RowSize), colorWhite, TextFormatFlags.VerticalCenter | TextFormatFlags.Left ); if (ship.Armor.IsMax) { TextRenderer.DrawText( g, "MAX", font7, new Rectangle(x + widthValue + 2 + 3, y, ColumnSizes[11] - 8, RowSize - 3), colorGray, TextFormatFlags.Bottom | TextFormatFlags.Left ); } else { TextRenderer.DrawText( g, "+" + ship.Armor.Shortfall.ToString(), font7, new Rectangle(x + widthValue + 3, y, ColumnSizes[11] - 8, RowSize - 3), colorGray, TextFormatFlags.Bottom | TextFormatFlags.Left ); } x += ColumnSizes[11]; #endregion #region AA widthValue = TextRenderer.MeasureText(ship.AA.Current.ToString(), this.Font).Width - 4; if (ship.AA.IsMax) { using (SolidBrush b = new SolidBrush(Color.FromArgb(0x7F, 0xDF, 0x6A, 0x0C))) g.FillRectangle(b, new Rectangle(x, y, ColumnSizes[12], RowSize)); } TextRenderer.DrawText( g, ship.AA.Current.ToString(), this.Font, new Rectangle(x + 3, y, ColumnSizes[12] - 8, RowSize), colorWhite, TextFormatFlags.VerticalCenter | TextFormatFlags.Left ); if (ship.AA.IsMax) { TextRenderer.DrawText( g, "MAX", font7, new Rectangle(x + widthValue + 2 + 3, y, ColumnSizes[12] - 8, RowSize - 3), colorGray, TextFormatFlags.Bottom | TextFormatFlags.Left ); } else { TextRenderer.DrawText( g, "+" + ship.AA.Shortfall.ToString(), font7, new Rectangle(x + widthValue + 3, y, ColumnSizes[12] - 8, RowSize - 3), colorGray, TextFormatFlags.Bottom | TextFormatFlags.Left ); } x += ColumnSizes[12]; #endregion #region ASW widthValue = TextRenderer.MeasureText(ship.ASW.Current.ToString(), this.Font).Width - 4; if (ship.ASW.IsMax) { using (SolidBrush b = new SolidBrush(Color.FromArgb(0x8B, 0xA2, 0xB0))) g.FillRectangle(b, new Rectangle(x, y, ColumnSizes[13], RowSize)); } TextRenderer.DrawText( g, ship.ASW.Current.ToString(), this.Font, new Rectangle(x + 3, y, ColumnSizes[13] - 8, RowSize), colorWhite, TextFormatFlags.VerticalCenter | TextFormatFlags.Left ); if (ship.ASW.IsMax) { TextRenderer.DrawText( g, "MAX", font7, new Rectangle(x + widthValue + 2 + 3, y, ColumnSizes[13] - 8, RowSize - 3), colorGray, TextFormatFlags.Bottom | TextFormatFlags.Left ); } else { TextRenderer.DrawText( g, "+" + ship.ASW.Shortfall.ToString(), font7, new Rectangle(x + widthValue + 3, y, ColumnSizes[13] - 8, RowSize - 3), colorGray, TextFormatFlags.Bottom | TextFormatFlags.Left ); } x += ColumnSizes[13]; #endregion #region Luck widthValue = TextRenderer.MeasureText(ship.Luck.Current.ToString(), this.Font).Width - 4; if (ship.Luck.IsMax) { using (SolidBrush b = new SolidBrush(Color.FromArgb(0x7F, 0x80, 0x80, 0x80))) g.FillRectangle(b, new Rectangle(x, y, ColumnSizes[14], RowSize)); } TextRenderer.DrawText( g, ship.Luck.Current.ToString(), this.Font, new Rectangle(x + 3, y, ColumnSizes[14] - 8, RowSize), colorWhite, TextFormatFlags.VerticalCenter | TextFormatFlags.Left ); if (ship.Luck.IsMax) { TextRenderer.DrawText( g, "MAX", font7, new Rectangle(x + widthValue + 2 + 3, y, ColumnSizes[14] - 8, RowSize - 3), colorGray, TextFormatFlags.Bottom | TextFormatFlags.Left ); } else { TextRenderer.DrawText( g, "+" + ship.Luck.Shortfall.ToString(), font7, new Rectangle(x + widthValue + 3, y, ColumnSizes[14] - 8, RowSize - 3), colorGray, TextFormatFlags.Bottom | TextFormatFlags.Left ); } x += ColumnSizes[14]; #endregion #region View Range TextRenderer.DrawText( g, ship.ViewRange.ToString(), this.Font, new Rectangle(x + 3, y, ColumnSizes[15] - 8, RowSize), colorWhite, TextFormatFlags.VerticalCenter | TextFormatFlags.Left ); x += ColumnSizes[15]; #endregion #region Sally Area if (ship.SallyArea > 0) { using (SolidBrush b = new SolidBrush(SallyArea.SallyAreaColor(ship.SallyArea))) g.FillRectangle(b, new Rectangle(x, y, ColumnSizes[16], RowSize)); TextRenderer.DrawText( g, SallyArea.SallyAreaName(ship.SallyArea), this.Font, new Rectangle(x + 3, y, ColumnSizes[16] - 8, RowSize), colorWhite, TextFormatFlags.VerticalCenter | TextFormatFlags.Left ); } x += ColumnSizes[16]; #endregion #region Repair Time if ((ship?.TimeToRepair ?? TimeSpan.Zero) != TimeSpan.Zero) { TextRenderer.DrawText( g, ship.RepairTimeString, this.Font, new Rectangle(x + 3, y, ColumnSizes[17] - 8, RowSize), colorWhite, TextFormatFlags.VerticalCenter | TextFormatFlags.Left ); } x += ColumnSizes[17]; #endregion g.DrawLine(p, 0, y + RowSize, Width, y + RowSize); y += RowSize + 3; idx++; } } #endregion } var ResultSize = new Size( ColumnSizes.Sum() + this.Padding.Left + this.Padding.Right + 1, ((Ships?.Count() ?? 0) * (RowSize + 1)) + this.Padding.Top + this.Padding.Bottom + 1 ); if (ResultSize.Width != LatestSize.Width || ResultSize.Height != LatestSize.Height) { LatestSize = ResultSize; this.PerformAutoScale(); this.PerformLayout(); this.Owner.RequestUpdate(); } }; }
public ShipListTable() { InitializeComponent(); this.Resize += (s, e) => { this.panelDataView.Location = new Point(1, this.RowSize); this.panelDataView.Size = new Size( this.ClientSize.Width - 2, this.ClientSize.Height - (this.RowSize - 1) - 2 ); this.RequestUpdate(); }; this.Paint += (s, e) => { var g = e.Graphics; var Width = this.Width - this.Padding.Left - this.Padding.Right; var Height = this.Height - this.Padding.Top - this.Padding.Bottom; g.Clear(this.BackColor); int x, y = 0; using (Pen p = new Pen(Color.FromArgb(83, 83, 83), 1.0f)) { g.DrawRectangle(p, new Rectangle(0, y, Width - 1, Height - y - 1)); g.DrawRectangle(p, new Rectangle(0, RowSize, Width - 1, Height - RowSize - 1 - 1)); #region Header Rendering x = this.panelDataView.AutoScrollPosition.X; y = 0; using (SolidBrush b = new SolidBrush(Color.FromArgb(0x20, 0x20, 0x20))) g.FillRectangle(b, new Rectangle(0, y, Width, RowSize)); g.DrawRectangle(p, new Rectangle(0, y, Width - 1, RowSize - 1)); for (var i = 0; i < ColumnSizes.Length; i++) { g.DrawRectangle(p, new Rectangle(x, 0, ColumnSizes[i], RowSize - 1)); TextRenderer.DrawText( g, Headers[i], this.Font, new Rectangle(x + 3, y, ColumnSizes[i] - 8, RowSize), Color.White, TextFormatFlags.VerticalCenter | TextFormatFlags.Left ); x += ColumnSizes[i]; } #endregion } }; tableView = new TableView(this); tableView.Margin = new Padding(0, 0, 0, 0); tableView.Padding = new Padding(0, 0, 0, 0); tableView.AutoSize = true; tableView.AutoSizeMode = AutoSizeMode.GrowAndShrink; panelDataView.Controls.Add(tableView); panelDataView.Scroll += (s, e) => this.Invalidate(new Rectangle(0, 0, this.Width, this.RowSize + 2)); }
/// <summary> /// OnPaintForeground method. /// </summary> /// <param name="e">PaintEventArgs instance.</param> protected virtual void OnPaintForeground(PaintEventArgs e) { Color borderColor; Color foreColor; if (this._isHovered && !this._isPressed && this.Enabled) { foreColor = ModernPaint.ForeColor.CheckBox.Hover(this.ThemeStyle); borderColor = ModernPaint.BorderColor.CheckBox.Hover(this.ThemeStyle); } else if (this._isHovered && this._isPressed && this.Enabled) { foreColor = ModernPaint.ForeColor.CheckBox.Press(this.ThemeStyle); borderColor = ModernPaint.BorderColor.CheckBox.Press(this.ThemeStyle); } else if (!this.Enabled) { foreColor = ModernPaint.ForeColor.CheckBox.Disabled(this.ThemeStyle); borderColor = ModernPaint.BorderColor.CheckBox.Disabled(this.ThemeStyle); } else { foreColor = !this.UseStyleColors ? ModernPaint.ForeColor.CheckBox.Normal(this.ThemeStyle) : ModernPaint.GetStyleColor(this.ColorStyle); borderColor = ModernPaint.BorderColor.CheckBox.Normal(this.ThemeStyle); } using (Pen pen = new Pen(borderColor)) { Rectangle boxRectangle = new Rectangle(this.StatusTextRightToLeft ? 0 : (this.ShowStatusText ? 30 : 0), 0, this.ClientRectangle.Width - (this.ShowStatusText ? 31 : 1), this.ClientRectangle.Height - 1); e.Graphics.DrawRectangle(pen, boxRectangle); } Color fillColor = this.Checked ? ModernPaint.GetStyleColor(this.ColorStyle) : ModernPaint.BorderColor.CheckBox.Normal(this.ThemeStyle); using (SolidBrush brush = new SolidBrush(fillColor)) { Rectangle boxRectangle = new Rectangle(this.StatusTextRightToLeft ? 2 : (this.ShowStatusText ? 32 : 2), 2, this.ClientRectangle.Width - (this.ShowStatusText ? 34 : 4), this.ClientRectangle.Height - 4); e.Graphics.FillRectangle(brush, boxRectangle); } Color backColor = this.BackColor; if (!this.UseCustomBackColor) { backColor = ModernPaint.BackColor.Form(this.ThemeStyle); } using (SolidBrush brush = new SolidBrush(backColor)) { int left = this.Checked ? this.Width - 11 : (this.ShowStatusText ? 30 : 0); Rectangle boxRectangle = new Rectangle(this.StatusTextRightToLeft ? left - 30 : left, 0, 11, this.ClientRectangle.Height); e.Graphics.FillRectangle(brush, boxRectangle); } using (SolidBrush brush = new SolidBrush(ModernPaint.BorderColor.CheckBox.Hover(this.ThemeStyle))) { int left = this.Checked ? this.Width - 10 : (this.ShowStatusText ? 30 : 0); Rectangle boxRectangle = new Rectangle(this.StatusTextRightToLeft ? left - 30 : left, 0, 10, this.ClientRectangle.Height); e.Graphics.FillRectangle(brush, boxRectangle); } if (this.ShowStatusText) { Rectangle textRectangle = new Rectangle(this.StatusTextRightToLeft ? this.ClientRectangle.Width - (this.ShowStatusText ? 31 : 1) : 0, 0, 30, this.ClientRectangle.Height); TextRenderer.DrawText(e.Graphics, this.Text, ModernFonts.Link(this.FontSize, this.FontWeight), textRectangle, foreColor, ModernPaint.GetTextFormatFlags(this.TextAlign)); } if (this.DisplayFocus && this._isFocused) { ControlPaint.DrawFocusRectangle(e.Graphics, this.ClientRectangle); } }
/// <summary> /// Gets the text rectangle. /// </summary> /// <param name="graphics">The graphics.</param> /// <returns>Rectangle.</returns> private Rectangle GetTextRectangle(Graphics graphics) { Size sz = TextRenderer.MeasureText(graphics, this.Text, this.Font, Size.Empty, TextFormatFlags.WordBreak); return(new Rectangle(Point.Empty, sz)); }
private int CalculateHeight() { return(TextRenderer.MeasureText("W", Font).Height); }
protected override void OnPaintBackground(PaintEventArgs e) { base.OnPaint(e); e.Graphics.SetClip(new Rectangle(margin, 0, Width - margin, Height)); double currentFrameX = 20 + margin + (currentFrame - frameLeft) * (Width - 40 - margin) / (frameRight - frameLeft); e.Graphics.FillRectangle(brush2, new Rectangle(0, 0, Width, Height)); e.Graphics.FillRectangle(brush3, new Rectangle(0, 0, Width, barHeight)); double step = 50 * (frameRight - frameLeft) / Width; if (step > 10) { step = Math.Round(step / 10.0) * 10; } else { step = Math.Round(Math.Max(1, step)); } if (lastFrame != startTime) { double max; if (frameRight < lastFrame) { max = Math.Min(frameRight + step, lastFrame); } else { max = frameRight - step; } for (double frame = Math.Floor(frameLeft / step) * step; frame <= max; frame += step) { double frameX = 20 + margin + (frame - frameLeft) * (Width - 40 - margin) / (frameRight - frameLeft); e.Graphics.DrawLine(pen1, new Point((int)frameX, barHeight), new Point((int)frameX, Height)); e.Graphics.DrawString("" + frame, font, brush4, new Point((int)frameX - TextRenderer.MeasureText("" + frame, font).Width / 2, 0)); } } if (frameRight == lastFrame) { //draw last frame regardless of the steps double x = Width - 20; e.Graphics.DrawLine(pen1, new Point((int)x, barHeight), new Point((int)x, Height)); e.Graphics.DrawString("" + lastFrame, font, brush4, new Point((int)x - TextRenderer.MeasureText("" + lastFrame, font).Width / 2, 0)); } /* * int lastY = value((int)(Math.Round(- 20+margin * (frameRight - frameLeft) / (Width - 40-margin) + frameLeft) + lastFrame + 1) % (lastFrame + 1)); * for (int x = 5; x < Width+10; x+=5) * { * e.Graphics.DrawLine(pen3, x - 5, lastY, x, lastY = * value((int)(Math.Round((x - 20+margin) * (frameRight - frameLeft) / (Width - 40-margin) + frameLeft) + lastFrame + 1) % (lastFrame + 1)) * ); * } */ }
/// <summary> /// Called when the non client area of the form needs to be painted. /// </summary> /// <param name="form">The form which gets drawn.</param> /// <param name="paintData">The paint data to use for drawing.</param> /// <returns><code>true</code> if the original painting should be suppressed, otherwise <code>false</code></returns> public override bool OnNcPaint(Form form, SkinningFormPaintData paintData) { if (form == null) { return(false); } bool isMaximized = form.WindowState == FormWindowState.Maximized; bool isMinimized = form.WindowState == FormWindowState.Minimized; // prepare bounds Rectangle windowBounds = paintData.Bounds; windowBounds.Location = Point.Empty; Rectangle captionBounds = windowBounds; Size borderSize = paintData.Borders; captionBounds.Height = borderSize.Height + paintData.CaptionHeight; Rectangle textBounds = captionBounds; Rectangle iconBounds = captionBounds; iconBounds.Inflate(-borderSize.Width, 0); iconBounds.Y += borderSize.Height; iconBounds.Height -= borderSize.Height; // Draw Caption bool active = paintData.Active; _formCaption.Draw(paintData.Graphics, captionBounds, active ? 0 : 1); // Paint Icon if (paintData.HasMenu && form.Icon != null) { iconBounds.Size = paintData.IconSize; Icon tmpIcon = new Icon(form.Icon, paintData.IconSize); iconBounds.Y = captionBounds.Y + (captionBounds.Height - iconBounds.Height) / 2; paintData.Graphics.DrawIcon(tmpIcon, iconBounds); textBounds.X = iconBounds.Right; iconBounds.Width -= iconBounds.Right; } // Paint Icons foreach (CaptionButtonPaintData data in paintData.CaptionButtons) { ControlPaintHelper painter = paintData.IsSmallCaption ? _formCaptionButtonSmall : _formCaptionButton; // Get Indices for imagestrip int iconIndex; int backgroundIndex; GetButtonData(data, paintData.Active, out iconIndex, out backgroundIndex); // get imageStrip for button icon ImageStrip iconStrip; switch (data.HitTest) { case HitTest.HTCLOSE: iconStrip = paintData.IsSmallCaption ? _formCloseIconSmall : _formCloseIcon; break; case HitTest.HTMAXBUTTON: if (isMaximized) { iconStrip = paintData.IsSmallCaption ? _formRestoreIconSmall : _formRestoreIcon; } else { iconStrip = paintData.IsSmallCaption ? _formMaximizeIconSmall : _formMaximizeIcon; } break; case HitTest.HTMINBUTTON: if (isMinimized) { iconStrip = paintData.IsSmallCaption ? _formRestoreIconSmall : _formRestoreIcon; } else { iconStrip = paintData.IsSmallCaption ? _formMinimizeIconSmall : _formMinimizeIcon; } break; default: continue; } // draw background if (backgroundIndex >= 0) { painter.Draw(paintData.Graphics, data.Bounds, backgroundIndex); } // draw Icon Rectangle b = data.Bounds; b.Y += 1; if (iconIndex >= 0) { iconStrip.Draw(paintData.Graphics, iconIndex, b, Rectangle.Empty, DrawingAlign.Center, DrawingAlign.Center); } // Ensure textbounds textBounds.Width -= data.Bounds.Width; } // draw text if (!string.IsNullOrEmpty(paintData.Text) && !textBounds.IsEmpty) { TextFormatFlags flags = TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis | TextFormatFlags.PreserveGraphicsClipping; if (_formIsTextCentered) { flags = flags | TextFormatFlags.HorizontalCenter; } Font font = paintData.IsSmallCaption ? SystemFonts.SmallCaptionFont : SystemFonts.CaptionFont; TextRenderer.DrawText(paintData.Graphics, paintData.Text, font, textBounds, paintData.Active ? _formActiveTitleColor : _formInactiveTitleColor, flags); } // exclude caption area from painting Region region = paintData.Graphics.Clip; region.Exclude(captionBounds); paintData.Graphics.Clip = region; // Paint borders and corners _formBorder.DrawFrame(paintData.Graphics, windowBounds, paintData.Active ? 0 : 1); paintData.Graphics.ResetClip(); return(true); }
/// <summary> /// Truncates a text string to fit within a given control width by replacing trimmed text with ellipses. /// </summary> /// <param name="text">String to be trimmed.</param> /// <param name="ctrl">text must fit within ctrl width. /// The ctrl's Font is used to measure the text string.</param> /// <param name="options">Format and alignment of ellipsis.</param> /// <returns>This function returns text trimmed to the specified witdh.</returns> public static string Compact(string text, Graphics g, int width, Font font, EllipsisFormat options) { if (string.IsNullOrEmpty(text)) { return(text); } // no aligment information if ((EllipsisFormat.Middle & options) == 0) { return(text); } if (g == null) { throw new ArgumentNullException("g"); } Size s = TextRenderer.MeasureText(g, text, font); // control is large enough to display the whole text if (s.Width <= width) { return(text); } string pre = ""; string mid = text; string post = ""; bool isPath = (EllipsisFormat.Path & options) != 0; // split path string into <drive><directory><filename> if (isPath) { pre = Path.GetPathRoot(text); mid = Path.GetDirectoryName(text).Substring(pre.Length); post = Path.GetFileName(text); } int len = 0; int seg = mid.Length; string fit = ""; // find the longest string that fits into // the control boundaries using bisection method while (seg > 1) { seg -= seg / 2; int left = len + seg; int right = mid.Length; if (left > right) { continue; } if ((EllipsisFormat.Middle & options) == EllipsisFormat.Middle) { right -= left / 2; left -= left / 2; } else if ((EllipsisFormat.Start & options) != 0) { right -= left; left = 0; } // trim at a word boundary using regular expressions if ((EllipsisFormat.Word & options) != 0) { if ((EllipsisFormat.End & options) != 0) { left -= prevWord.Match(mid, 0, left).Length; } if ((EllipsisFormat.Start & options) != 0) { right += nextWord.Match(mid, right).Length; } } // build and measure a candidate string with ellipsis string tst = mid.Substring(0, left) + EllipsisChars + mid.Substring(right); // restore path with <drive> and <filename> if (isPath) { tst = Path.Combine(Path.Combine(pre, tst), post); } s = TextRenderer.MeasureText(g, tst, font); // candidate string fits into control boundaries, try a longer string // stop when seg <= 1 if (s.Width <= width) { len += seg; fit = tst; } } if (len == 0) // string can't fit into control { // "path" mode is off, just return ellipsis characters if (!isPath) { return(EllipsisChars); } // <drive> and <directory> are empty, return <filename> if (pre.Length == 0 && mid.Length == 0) { return(post); } // measure "C:\...\filename.ext" fit = Path.Combine(Path.Combine(pre, EllipsisChars), post); s = TextRenderer.MeasureText(g, fit, font); // if still not fit then return "...\filename.ext" if (s.Width > width) { fit = Path.Combine(EllipsisChars, post); } } return(fit); }
/// <summary> /// Measures the size of the button /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// <returns></returns> public override Size MeasureSize(object sender, RibbonElementMeasureSizeEventArgs e) { if (!Visible && !Owner.IsDesignMode()) { SetLastMeasuredSize(new Size(0, 0)); return(LastMeasuredSize); } var theSize = GetNearestSize(e.SizeMode); var widthSum = Owner.ItemMargin.Horizontal; var heightSum = Owner.ItemMargin.Vertical; var largeHeight = OwnerPanel == null ? 0 : OwnerPanel.ContentBounds.Height - Owner.ItemPadding.Vertical; // -Owner.ItemMargin.Vertical; //58; var simg = SmallImage != null ? SmallImage.Size : Size.Empty; var img = Image != null ? Image.Size : Size.Empty; var sz = Size.Empty; switch (theSize) { case RibbonElementSizeMode.Large: case RibbonElementSizeMode.Overflow: sz = MeasureStringLargeSize(e.Graphics, Text, Owner.Font); if (!string.IsNullOrEmpty(Text)) { widthSum += Math.Max(sz.Width + 1, img.Width); //Got off the patch site from logicalerror //heightSum = largeHeight; heightSum = Math.Max(0, largeHeight); } else { widthSum += img.Width; heightSum += img.Height; } break; case RibbonElementSizeMode.DropDown: sz = TextRenderer.MeasureText(Text, Owner.Font); if (!string.IsNullOrEmpty(Text)) { widthSum += sz.Width + 1; } widthSum += simg.Width + Owner.ItemMargin.Horizontal; heightSum += Math.Max(sz.Height, simg.Height); heightSum += 2; break; case RibbonElementSizeMode.Medium: sz = TextRenderer.MeasureText(Text, Owner.Font); if (!string.IsNullOrEmpty(Text)) { widthSum += sz.Width + 1; } widthSum += simg.Width + Owner.ItemMargin.Horizontal; heightSum += Math.Max(sz.Height, simg.Height); break; case RibbonElementSizeMode.Compact: widthSum += simg.Width; heightSum += simg.Height; break; default: throw new ApplicationException("SizeMode not supported: " + e.SizeMode); } //if (theSize == RibbonElementSizeMode.DropDown) //{ // heightSum += 2; //} switch (Style) { case RibbonButtonStyle.DropDown: case RibbonButtonStyle.SplitDropDown: // drawing size calculation for DropDown and SplitDropDown is identical widthSum += arrowWidth + _dropDownMargin.Horizontal; break; case RibbonButtonStyle.DropDownListItem: break; } //check the minimum and mazimum size properties but only in large mode if (theSize == RibbonElementSizeMode.Large) { //Minimum Size if (MinimumSize.Height > 0 && heightSum < MinimumSize.Height) { heightSum = MinimumSize.Height; } if (MinimumSize.Width > 0 && widthSum < MinimumSize.Width) { widthSum = MinimumSize.Width; } //Maximum Size if (MaximumSize.Height > 0 && heightSum > MaximumSize.Height) { heightSum = MaximumSize.Height; } if (MaximumSize.Width > 0 && widthSum > MaximumSize.Width) { widthSum = MaximumSize.Width; } } SetLastMeasuredSize(new Size(widthSum, heightSum)); return(LastMeasuredSize); }
/// <summary> /// Returns the width that will take the control /// </summary> /// <returns></returns> public int GetWidth() { return(_listOfButtons.Sum(button => TextRenderer.MeasureText(button, Font, ClientSize, TextFormatFlags.VerticalCenter | TextFormatFlags.Left | TextFormatFlags.NoPadding).Width + SpaceBetweenText)); }
private void DrawTab_Document(Graphics g, TabVS2003 tab, Rectangle rect) { Rectangle rectText = rect; if (DockPane.DockPanel.ShowDocumentIcon) { rectText.X += DocumentIconWidth + DocumentIconGapLeft; rectText.Width -= DocumentIconWidth + DocumentIconGapLeft; } if (DockPane.ActiveContent == tab.Content) { g.FillRectangle(ActiveBackBrush, rect); g.DrawLine(OutlineOuterPen, rect.X, rect.Y, rect.X, rect.Y + rect.Height); g.DrawLine(OutlineOuterPen, rect.X, rect.Y, rect.X + rect.Width - 1, rect.Y); g.DrawLine(OutlineInnerPen, rect.X + rect.Width - 1, rect.Y, rect.X + rect.Width - 1, rect.Y + rect.Height - 1); if (DockPane.DockPanel.ShowDocumentIcon) { Icon icon = (tab.Content as Form).Icon; Rectangle rectIcon = new Rectangle( rect.X + DocumentIconGapLeft, rect.Y + (rect.Height - DocumentIconHeight) / 2, DocumentIconWidth, DocumentIconHeight); g.DrawIcon(tab.ContentForm.Icon, rectIcon); } if (DockPane.IsActiveDocumentPane) { using (Font boldFont = new Font(this.Font, FontStyle.Bold)) { TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, boldFont, rectText, ActiveTextColor, DocumentTextFormat); } } else { TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, Font, rectText, InactiveTextColor, DocumentTextFormat); } } else { if (Tabs.IndexOf(DockPane.ActiveContent) != Tabs.IndexOf(tab) + 1) { g.DrawLine(TabSeperatorPen, rect.X + rect.Width - 1, rect.Y, rect.X + rect.Width - 1, rect.Y + rect.Height - 1 - DocumentTabGapTop); } if (DockPane.DockPanel.ShowDocumentIcon) { Icon icon = tab.ContentForm.Icon; Rectangle rectIcon = new Rectangle( rect.X + DocumentIconGapLeft, rect.Y + (rect.Height - DocumentIconHeight) / 2, DocumentIconWidth, DocumentIconHeight); g.DrawIcon(tab.ContentForm.Icon, rectIcon); } TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, Font, rectText, InactiveTextColor, DocumentTextFormat); } }
// returns a rectangle because it's possible that the top,left are outside of the 0,0 requested position. public static Rectangle Measure(String text, Graphics graphics, Font font, DrawMethod drawMethod = DrawMethod.Graphics, TextFormatFlags textFormatFlags = TextFormatFlags.Default, Rectangle?rect = null) { if (String.IsNullOrEmpty(text)) { return(Rectangle.Empty); } MultiKey mk = new MultiKey(text, graphics.TextRenderingHint, font, drawMethod, textFormatFlags, rect); //if (drawMethod == DrawMethod.Graphics) // mk = new MultiKey(text, graphics.TextRenderingHint, font, drawMethod); //else { // mk = new Object o = ht[mk]; if (o != null) { return((Rectangle)o); } Size size = Size.Empty; if (rect.HasValue) { var r2 = rect.Value; size = r2.Size; r2.Location = Point.Empty; rect = r2; } else { size = (drawMethod == DrawMethod.Graphics ? graphics.MeasureString(text, font).ToSize() : TextRenderer.MeasureText(graphics, text, font, Size.Empty, textFormatFlags)); } int w = size.Width; int h = size.Height; if (w == 0 || h == 0) { return(Rectangle.Empty); } Bitmap bitmap = new Bitmap(w, h, graphics); Graphics g2 = Graphics.FromImage(bitmap); g2.TextRenderingHint = graphics.TextRenderingHint; g2.SmoothingMode = graphics.SmoothingMode; g2.Clear(Color.White); if (drawMethod == DrawMethod.Graphics) { g2.DrawString(text, font, Brushes.Black, 0, 0); } else { // always specify a bounding rectangle. Otherwise if flags contains VerticalCenter it will be half cutoff above point (0,0) Rectangle r2 = (rect.HasValue ? rect.Value : new Rectangle(Point.Empty, size)); TextRenderer.DrawText(g2, text, font, r2, Color.Black, Color.White, textFormatFlags); } int left, right, top, bottom; left = right = top = bottom = -1; // scanning saves about 50-60% of having to scan the entire image for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { Color c = bitmap.GetPixel(i, j); if (c.R != 255 || c.G != 255 || c.B != 255) { left = i; break; } } if (left >= 0) { break; } } if (left == -1) { return(Rectangle.Empty); } for (int i = w - 1; i >= 0; i--) { for (int j = 0; j < h; j++) { Color c = bitmap.GetPixel(i, j); if (c.R != 255 || c.G != 255 || c.B != 255) { right = i; break; } } if (right >= 0) { break; } } for (int j = 0; j < h; j++) { for (int i = left; i <= right; i++) { Color c = bitmap.GetPixel(i, j); if (c.R != 255 || c.G != 255 || c.B != 255) { top = j; break; } } if (top >= 0) { break; } } for (int j = h - 1; j >= 0; j--) { for (int i = left; i <= right; i++) { Color c = bitmap.GetPixel(i, j); if (c.R != 255 || c.G != 255 || c.B != 255) { bottom = j; break; } } if (bottom >= 0) { break; } } g2.Dispose(); bitmap.Dispose(); var r = new Rectangle(left, top, (right - left) + 1, (bottom - top) + 1); ht[mk] = r; return(r); }
public void Draw(TextRenderer textRenderer, ShapeRenderer shapeRenderer) { textRenderer.Draw(this.Value, this.Position, this.Origin, 0f, this.Colour); }
public void TextRenderer_CanRenderColoredStrings() { var spriteBatch = default(SpriteBatch); var spriteFont = default(SpriteFont); var textRenderer = default(TextRenderer); var result = GivenAnUltravioletApplication() .WithContent(content => { spriteBatch = SpriteBatch.Create(); spriteFont = content.Load<SpriteFont>("Fonts/SegoeUI"); textRenderer = new TextRenderer(); }) .Render(uv => { spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend); var settings = new TextLayoutSettings(spriteFont, null, null, TextFlags.Standard); textRenderer.Draw(spriteBatch, "Hello, |c:FFFF0000|world|c|! This is a |c:FF00FF00|colored|c| |c:FF0000FF|string|c|!", Vector2.Zero, Color.White, settings); spriteBatch.End(); }); TheResultingImage(result) .ShouldMatch(@"Resources\Expected\Graphics\Graphics2D\Text\TextRenderer_CanRenderColoredStrings.png"); }
private void DrawTabPages(Graphics g) { using (SolidBrush brush = new SolidBrush(this._pageColor)) { int x = 2; int y = this.ItemSize.Height; int width = this.Width - 2; int height = this.Height - this.ItemSize.Height; g.FillRectangle(brush, x, y, width, height); g.DrawRectangle(new Pen(this._borderColor), x, y, width - 1, height - 1); } Rectangle tabRect = Rectangle.Empty; Point cursorPoint = this.PointToClient(MousePosition); for (int i = 0; i < base.TabCount; i++) { TabPage page = this.TabPages[i]; tabRect = this.GetTabRect(i); Color baseColor = Color.Yellow; Image baseTabHeaderImage = null; Image btnArrowImage = null; if (this.SelectedIndex == i)//是否选中 { baseTabHeaderImage = AssemblyHelper.GetImage("QQ.AppFramework.TabControl.tabbutton_check.png"); Point contextMenuLocation = this.PointToScreen(new Point(this._btnArrowRect.Left, this._btnArrowRect.Top + this._btnArrowRect.Height + 5)); //ContextMenuStrip contextMenuStrip = this.TabPages[i].ContextMenuStrip; //if (contextMenuStrip != null) //{ // contextMenuStrip.Closed -= new ToolStripDropDownClosedEventHandler(contextMenuStrip_Closed); // contextMenuStrip.Closed += new ToolStripDropDownClosedEventHandler(contextMenuStrip_Closed); // if (contextMenuLocation.X + contextMenuStrip.Width > // Screen.PrimaryScreen.WorkingArea.Width - 20) // { // contextMenuLocation.X = Screen.PrimaryScreen.WorkingArea.Width - // contextMenuStrip.Width - 50; // } // if (tabRect.Contains(cursorPoint)) // { // if (this._isFocus) // { // btnArrowImage = AssemblyHelper.GetImage("QQ.TabControl.main_tabbtn_down.png"); // contextMenuStrip.Show(contextMenuLocation); // } // else // { // btnArrowImage = AssemblyHelper.GetImage("QQ.TabControl.main_tabbtn_highlight.png"); // } // this._btnArrowRect = new Rectangle(tabRect.X + tabRect.Width - btnArrowImage.Width, tabRect.Y, btnArrowImage.Width, btnArrowImage.Height); // } // else if (this._isFocus) // { // btnArrowImage = AssemblyHelper.GetImage("QQ.TabControl.main_tabbtn_down.png"); // contextMenuStrip.Show(contextMenuLocation); // } //} } else if (tabRect.Contains(cursorPoint))//鼠标滑过 { baseTabHeaderImage = AssemblyHelper.GetImage("QQ.AppFramework.TabControl.tabbutton_highlight.png"); } if (baseTabHeaderImage != null) { if (this.SelectedIndex == i) { if (this.SelectedIndex == this.TabCount - 1) { tabRect.Inflate(2, 0); } else { tabRect.Inflate(1, 0); } } this.DrawImage(g, baseTabHeaderImage, tabRect); if (btnArrowImage != null) { //当鼠标进入当前选中的的选项卡时,显示下拉按钮 g.DrawImage(btnArrowImage, this._btnArrowRect); } } TextRenderer.DrawText(g, page.Text, page.Font, tabRect, page.ForeColor); } }
public void TextRenderer_CanAlignTextWithinAnArea() { var spriteBatch = default(SpriteBatch); var spriteFont = default(SpriteFont); var textRenderer = default(TextRenderer); var result = GivenAnUltravioletApplication() .WithContent(content => { spriteBatch = SpriteBatch.Create(); spriteFont = content.Load<SpriteFont>("Fonts/SegoeUI"); textRenderer = new TextRenderer(); }) .Render(uv => { var window = uv.GetPlatform().Windows.GetPrimary(); var width = window.ClientSize.Width; var height = window.ClientSize.Height; spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend); var settingsTopLeft = new TextLayoutSettings(spriteFont, width, height, TextFlags.AlignTop | TextFlags.AlignLeft); textRenderer.Draw(spriteBatch, "Aligned top left", Vector2.Zero, Color.White, settingsTopLeft); var settingsTopCenter = new TextLayoutSettings(spriteFont, width, height, TextFlags.AlignTop | TextFlags.AlignCenter); textRenderer.Draw(spriteBatch, "Aligned top center", Vector2.Zero, Color.White, settingsTopCenter); var settingsTopRight = new TextLayoutSettings(spriteFont, width, height, TextFlags.AlignTop | TextFlags.AlignRight); textRenderer.Draw(spriteBatch, "Aligned top right", Vector2.Zero, Color.White, settingsTopRight); var settingsMiddleLeft = new TextLayoutSettings(spriteFont, width, height, TextFlags.AlignMiddle | TextFlags.AlignLeft); textRenderer.Draw(spriteBatch, "Aligned middle left", Vector2.Zero, Color.White, settingsMiddleLeft); var settingsMiddleCenter = new TextLayoutSettings(spriteFont, width, height, TextFlags.AlignMiddle | TextFlags.AlignCenter); textRenderer.Draw(spriteBatch, "Aligned middle center", Vector2.Zero, Color.White, settingsMiddleCenter); var settingsMiddleRight = new TextLayoutSettings(spriteFont, width, height, TextFlags.AlignMiddle | TextFlags.AlignRight); textRenderer.Draw(spriteBatch, "Aligned middle right", Vector2.Zero, Color.White, settingsMiddleRight); var settingsBottomLeft = new TextLayoutSettings(spriteFont, width, height, TextFlags.AlignBottom | TextFlags.AlignLeft); textRenderer.Draw(spriteBatch, "Aligned bottom left", Vector2.Zero, Color.White, settingsBottomLeft); var settingsBottomCenter = new TextLayoutSettings(spriteFont, width, height, TextFlags.AlignBottom | TextFlags.AlignCenter); textRenderer.Draw(spriteBatch, "Aligned bottom center", Vector2.Zero, Color.White, settingsBottomCenter); var settingsBottomRight = new TextLayoutSettings(spriteFont, width, height, TextFlags.AlignBottom | TextFlags.AlignRight); textRenderer.Draw(spriteBatch, "Aligned bottom right", Vector2.Zero, Color.White, settingsBottomRight); spriteBatch.End(); }); TheResultingImage(result) .ShouldMatch(@"Resources\Expected\Graphics\Graphics2D\Text\TextRenderer_CanAlignTextWithinAnArea.png"); }
public void BehaviorAutoSize() { if (TestHelper.RunningOnUnix) { Assert.Ignore("Depends on font measurements, corresponds to windows"); } Form f = new Form(); f.ShowInTaskbar = false; f.Show(); Image i = new Bitmap(20, 20); String s = "My test string"; Button b = new Button(); Size s_size = TextRenderer.MeasureText(s, new Button().Font); b.UseCompatibleTextRendering = false; b.AutoSize = true; b.AutoSizeMode = AutoSizeMode.GrowAndShrink; b.Text = s; f.Controls.Add(b); // Text only b.TextImageRelation = TextImageRelation.Overlay; Assert.AreEqual(new Size(s_size.Width + 10, s_size.Height + 10), b.Size, "A1"); b.TextImageRelation = TextImageRelation.ImageAboveText; Assert.AreEqual(new Size(s_size.Width + 10, s_size.Height + 10), b.Size, "A2"); b.TextImageRelation = TextImageRelation.ImageBeforeText; Assert.AreEqual(new Size(s_size.Width + 10, s_size.Height + 10), b.Size, "A3"); b.TextImageRelation = TextImageRelation.TextAboveImage; Assert.AreEqual(new Size(s_size.Width + 10, s_size.Height + 10), b.Size, "A4"); b.TextImageRelation = TextImageRelation.TextBeforeImage; Assert.AreEqual(new Size(s_size.Width + 10, s_size.Height + 10), b.Size, "A5"); // Text and Image b.Image = i; b.TextImageRelation = TextImageRelation.Overlay; Assert.AreEqual(new Size(s_size.Width + 10, i.Height + 6), b.Size, "A6"); b.TextImageRelation = TextImageRelation.ImageAboveText; Assert.AreEqual(new Size(s_size.Width + 10, s_size.Height + i.Height + 10), b.Size, "A7"); b.TextImageRelation = TextImageRelation.ImageBeforeText; Assert.AreEqual(new Size(s_size.Width + i.Width + 10, i.Height + 6), b.Size, "A8"); b.TextImageRelation = TextImageRelation.TextAboveImage; Assert.AreEqual(new Size(s_size.Width + 10, s_size.Height + i.Height + 10), b.Size, "A9"); b.TextImageRelation = TextImageRelation.TextBeforeImage; Assert.AreEqual(new Size(s_size.Width + i.Width + 10, i.Height + 6), b.Size, "A10"); // Image only b.Text = string.Empty; b.TextImageRelation = TextImageRelation.Overlay; Assert.AreEqual(new Size(i.Height + 6, i.Height + 6), b.Size, "A11"); b.TextImageRelation = TextImageRelation.ImageAboveText; Assert.AreEqual(new Size(i.Height + 6, i.Height + 6), b.Size, "A12"); b.TextImageRelation = TextImageRelation.ImageBeforeText; Assert.AreEqual(new Size(i.Height + 6, i.Height + 6), b.Size, "A13"); b.TextImageRelation = TextImageRelation.TextAboveImage; Assert.AreEqual(new Size(i.Height + 6, i.Height + 6), b.Size, "A14"); b.TextImageRelation = TextImageRelation.TextBeforeImage; Assert.AreEqual(new Size(i.Height + 6, i.Height + 6), b.Size, "A15"); // Neither b.Image = null; b.TextImageRelation = TextImageRelation.Overlay; Assert.AreEqual(new Size(6, 6), b.Size, "A16"); b.TextImageRelation = TextImageRelation.ImageAboveText; Assert.AreEqual(new Size(6, 6), b.Size, "A17"); b.TextImageRelation = TextImageRelation.ImageBeforeText; Assert.AreEqual(new Size(6, 6), b.Size, "A18"); b.TextImageRelation = TextImageRelation.TextAboveImage; Assert.AreEqual(new Size(6, 6), b.Size, "A19"); b.TextImageRelation = TextImageRelation.TextBeforeImage; Assert.AreEqual(new Size(6, 6), b.Size, "A20"); // Padding b.Padding = new Padding(5, 10, 15, 20); Assert.AreEqual(new Size(6 + b.Padding.Horizontal, 6 + b.Padding.Vertical), b.Size, "A21"); f.Dispose(); }
//protected int Zoom(int value, float zoom) //{ // return (int)Math.Ceiling(value * zoom); //} protected virtual Size CalculateNodeSize(Topic topic, MindMapLayoutArgs e) { //if (topic.CustomWidth.HasValue && topic.CustomHeight.HasValue) // return new Size(topic.CustomWidth.Value, topic.CustomHeight.Value); // Size proposedSize = Size.Empty; if (topic.CustomWidth.HasValue && topic.CustomWidth.Value > 0) { proposedSize.Width = topic.CustomWidth.Value - topic.Style.Padding.Horizontal; } if (topic.CustomHeight.HasValue && topic.CustomHeight.Value > 0) { proposedSize.Height = topic.CustomHeight.Value - topic.Style.Padding.Vertical; } // Icon Size //Rectangle iconBounds = Rectangle.Empty; //if (topic.Icon != null) //{ // iconBounds = new Rectangle(0, 0, topic.Icon.Width, topic.Icon.Height); // if (proposedSize.Width > 0) // proposedSize.Width -= topic.IconBounds.Width + +topic.Style.IconPadding; //} // Text Size Rectangle rectText = Rectangle.Empty; Font font = topic.Style.Font != null ? topic.Style.Font : e.Font; Size textSize; if (e.Graphics == null) { textSize = TextRenderer.MeasureText(topic.Text, font, proposedSize); } else { textSize = Size.Ceiling(e.Graphics.MeasureString(topic.Text, font, new SizeF(proposedSize.Width, proposedSize.Height))); } rectText = new Rectangle(Point.Empty, textSize); // Widgets Size //var widgetAligns = new WidgetAlignment[] { WidgetAlignment.Left, WidgetAlignment.Top, WidgetAlignment.Right, WidgetAlignment.Bottom }; var rectLeft = CalculateWidgets(topic, WidgetAlignment.Left, e); var rectTop = CalculateWidgets(topic, WidgetAlignment.Top, e); var rectRight = CalculateWidgets(topic, WidgetAlignment.Right, e); var rectBottom = CalculateWidgets(topic, WidgetAlignment.Bottom, e); int maxWidth = Helper.GetMax(rectText.Width, rectTop.Width, rectBottom.Width) + rectLeft.Width + rectRight.Width; int totalHeight = Helper.GetMax(rectText.Height + rectTop.Height + rectBottom.Height, rectLeft.Height, rectRight.Height); rectText.Width = Helper.GetMax(rectText.Width, rectTop.Width, rectBottom.Width); // Desc Size if (e.ShowRemarkIcon && topic.HaveRemark) { maxWidth += 16; } // Calculate Size Size size = new Size(maxWidth + topic.Padding.Horizontal, totalHeight + topic.Padding.Vertical); //if (!iconBounds.IsEmpty) //{ // size.Width += topic.IconPadding + iconBounds.Width; // size.Height = Math.Max(topic.IconPadding + iconBounds.Height, size.Height); //} size.Width = Math.Max(MinNodeSize.Width, size.Width); size.Height = Math.Max(MinNodeSize.Height, size.Height); if (topic.CustomWidth.HasValue) { size.Width = topic.CustomWidth.Value; } else if (topic.CustomHeight.HasValue) { size.Height = topic.CustomHeight.Value; } // var rect = new Rectangle(0, 0, size.Width, size.Height); rect = rect.Inflate(topic.Style.Padding); // Text Location // Widgets Location int hh1 = rectText.Height + rectTop.Height + rectBottom.Height; if (hh1 < rect.Height) { int hh = (rect.Height - hh1) / 3; rectText.Height += hh; rectTop.Height += hh; rectBottom.Height += hh; } if (!rectText.IsEmpty) { rectText = new Rectangle( rect.X + rectLeft.Width, rect.Y + rectTop.Height, rect.Width - rectLeft.Width - rectRight.Width, rect.Height - rectTop.Height - rectBottom.Height); } rectLeft.Height = rectRight.Height = Helper.GetMax(rectLeft.Height, rectRight.Height, rectText.Height + rectTop.Height + rectBottom.Height); rectLeft.Y = rectRight.Y = rect.Y; rectLeft.X = rect.X; rectRight.X = rectLeft.Right + rectText.Width; rectTop.X = rectBottom.X = rectText.Left; rectTop.Width = rectBottom.Width = rectText.Width; rectTop.Y = rect.Y; rectBottom.Y = rectText.Bottom; topic.TextBounds = rectText; ResetWidgetLocation(e, topic, WidgetAlignment.Left, rectLeft); ResetWidgetLocation(e, topic, WidgetAlignment.Top, rectTop); ResetWidgetLocation(e, topic, WidgetAlignment.Right, rectRight); ResetWidgetLocation(e, topic, WidgetAlignment.Bottom, rectBottom); // return(size); }
private void pictureBoxProgress_Paint(object sender, PaintEventArgs e) { Graphics canvas = e.Graphics; progressBarValue += (progressBarTarget - progressBarValue) * 0.2F; if (capturing) { progressBarFade += (1 - progressBarFade) * .1F; } else { progressBarFade += (0 - progressBarFade) * .1F; } canvas.FillRectangle(new SolidBrush(Color.FromArgb(255, 154, 205 + (int)(progressBarValue * 20), 50 + (int)(progressBarValue * 80))), 0, 0, this.Width * progressBarValue, this.Height); canvas.FillRectangle(new SolidBrush(Color.FromArgb(255, 164, 215 + (int)(progressBarValue * 20), 60 + (int)(progressBarValue * 80))), 0, 0, this.Width * progressBarValue, 8); canvas.FillRectangle(new SolidBrush(Color.FromArgb(255, 174, 225 + (int)(progressBarValue * 20), 70 + (int)(progressBarValue * 80))), 0, 2, this.Width * progressBarValue, 4); if (progressBarFade > .1 && numericUpDownImageBatch.Value > 1) { var str = "Q: " + (imageQueue.Count + 1).ToString(); TextRenderer.DrawText(canvas, str, progressBarFont, new Point(pictureBoxProgress.Width - 5 - (int)(((TextRenderer.MeasureText(str, progressBarFont).Width)) * progressBarFade), 0), Color.Black); } }
/// <summary> /// Return a pointer to the unamanged version of this callback. /// </summary> /// <param name="callback">The callback.</param> /// <returns>A pointer to a shadow c++ callback</returns> public static IntPtr ToIntPtr(TextRenderer callback) { return ToIntPtr<TextRenderer>(callback); }
void DrawCaption(Graphics g) { if (ClientRectangle.Width == 0 || ClientRectangle.Height == 0) { return; } Rectangle rect = ClientRectangle; using (var brush = new SolidBrush(DockPane.DockPanel.BackColor)) g.FillRectangle(brush, rect); ColorBlend captionBg; if (DockPane.IsActivated) { captionBg = ActiveBackColorGradientBlend; } else { captionBg = InactiveBackColorGradientBlend; } using (var captionBrush = new LinearGradientBrush(rect, Color.Empty, Color.Empty, LinearGradientMode.Vertical)) using (var captionPath = RoundedRectangle.Construct(rect, 4, RoundedCorner.TopLeft | RoundedCorner.TopRight)) { captionBrush.InterpolationColors = captionBg; g.FillPath(captionBrush, captionPath); } Rectangle rectCaption = rect; Rectangle rectCaptionText = rectCaption; rectCaptionText.X += TextGapLeft; rectCaptionText.Width -= TextGapLeft + TextGapRight; rectCaptionText.Width -= ButtonGapLeft + ButtonClose.Width + ButtonGapRight; if (ShouldShowAutoHideButton) { rectCaptionText.Width -= ButtonAutoHide.Width + ButtonGapBetween; } if (HasTabPageContextMenu) { rectCaptionText.Width -= ButtonOptions.Width + ButtonGapBetween; } rectCaptionText.Y += TextGapTop; rectCaptionText.Height -= TextGapTop + TextGapBottom; Color colorText; if (DockPane.IsActivated) { colorText = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.TextColor; } else { colorText = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.TextColor; } TextRenderer.DrawText(g, DockPane.CaptionText, TextFont, DrawHelper.RtlTransform(this, rectCaptionText), colorText, TextFormat); Rectangle rectDotsStrip = rectCaptionText; int textLength = (int)g.MeasureString(DockPane.CaptionText, TextFont).Width + TextGapLeft; rectDotsStrip.X += textLength; rectDotsStrip.Width -= textLength; rectDotsStrip.Height = ClientRectangle.Height; Color dotsColor; if (DockPane.IsActivated) { dotsColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.EndColor; } else { dotsColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.EndColor; } }
/// <summary> /// Draws text using the specified client drawing context. /// </summary> /// <remarks> /// To draw text with this method, a textLayout object needs to be created by the application using <see cref="SharpDX.DirectWrite.Factory.CreateTextLayout"/>. After the textLayout object is obtained, the application calls the IDWriteTextLayout::Draw method to draw the text, decorations, and inline objects. The actual drawing is done through the callback interface passed in as the textRenderer argument; there, the corresponding DrawGlyphRun API is called. /// </remarks> /// <param name="renderer">Pointer to the set of callback functions used to draw parts of a text string.</param> /// <param name="originX">The x-coordinate of the layout's left side.</param> /// <param name="originY">The y-coordinate of the layout's top side.</param> /// <returns>If the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> /// <unmanaged>HRESULT Draw([None] void* clientDrawingContext,[None] IDWriteTextRenderer* renderer,[None] FLOAT originX,[None] FLOAT originY)</unmanaged> public void Draw(TextRenderer renderer, float originX, float originY) { Draw(null, renderer, originX, originY); }
protected override void Paint(System.Drawing.Graphics g, System.Drawing.Rectangle clipBounds, System.Drawing.Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts) { if (Convert.ToInt16(value) == 0 || value == null) { value = 0; } int progressVal = Convert.ToInt32(value); float percentage = ((float)progressVal / 100.0f); Brush backColorBrush = new SolidBrush(cellStyle.BackColor); Brush foreColorBrush = new SolidBrush(cellStyle.ForeColor); // Рисование рамки ячейки base.Paint(g, clipBounds, cellBounds, rowIndex, cellState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, (paintParts & ~DataGridViewPaintParts.ContentForeground)); float posX = cellBounds.X; float posY = cellBounds.Y; float textWidth = TextRenderer.MeasureText(progressVal.ToString() + "%", cellStyle.Font).Width; float textHeight = TextRenderer.MeasureText(progressVal.ToString() + "%", cellStyle.Font).Height; // Положение текста в зависимости от выравнивания в ячейке switch (cellStyle.Alignment) { case DataGridViewContentAlignment.BottomCenter: posX = cellBounds.X + (cellBounds.Width / 2) - textWidth / 2; posY = cellBounds.Y + cellBounds.Height - textHeight; break; case DataGridViewContentAlignment.BottomLeft: posX = cellBounds.X; posY = cellBounds.Y + cellBounds.Height - textHeight; break; case DataGridViewContentAlignment.BottomRight: posX = cellBounds.X + cellBounds.Width - textWidth; posY = cellBounds.Y + cellBounds.Height - textHeight; break; case DataGridViewContentAlignment.MiddleCenter: posX = cellBounds.X + (cellBounds.Width / 2) - textWidth / 2; posY = cellBounds.Y + (cellBounds.Height / 2) - textHeight / 2; break; case DataGridViewContentAlignment.MiddleLeft: posX = cellBounds.X; posY = cellBounds.Y + (cellBounds.Height / 2) - textHeight / 2; break; case DataGridViewContentAlignment.MiddleRight: posX = cellBounds.X + cellBounds.Width - textWidth; posY = cellBounds.Y + (cellBounds.Height / 2) - textHeight / 2; break; case DataGridViewContentAlignment.TopCenter: posX = cellBounds.X + (cellBounds.Width / 2) - textWidth / 2; posY = cellBounds.Y; break; case DataGridViewContentAlignment.TopLeft: posX = cellBounds.X; posY = cellBounds.Y; break; case DataGridViewContentAlignment.TopRight: posX = cellBounds.X + cellBounds.Width - textWidth; posY = cellBounds.Y; break; } if (percentage >= 0.0) { // Рисование прогресса g.FillRectangle(new SolidBrush(_ProgressBarColor), cellBounds.X + 2, cellBounds.Y + 2, Convert.ToInt32((percentage * cellBounds.Width * 0.8)), cellBounds.Height / 1 - 5); // Рисование текста g.DrawString(progressVal.ToString() + "%", cellStyle.Font, foreColorBrush, posX, posY); } else { // При отрицательном значении отображается только текст if (this.DataGridView.CurrentRow.Index == rowIndex) { g.DrawString(progressVal.ToString() + "%", cellStyle.Font, new SolidBrush(cellStyle.SelectionForeColor), posX, posX); } else { g.DrawString(progressVal.ToString() + "%", cellStyle.Font, foreColorBrush, posX, posY); } } }