c# - How to draw text of multiple sizes aligned on line with TextRenderer? -
this question has answer here:
i have array of classes contains text , font. want draw text aligned on line independently on font size. thought can subtract font height y-positiontion of line , draw text on new position bit difficult because of top , bottom padding added text gdi. calculation works right, text floats somewhere in middle of rectangle should in. found out can set textformatflags
nopadding
helps left , right padding , text still floats above line. searching long time way rid of padding, didn't found this. code:
public static void drawtextonline(string text, font font, graphics graphics, color color, int x, int dliney) { float uppery = dliney - getfontascent(font); point point = new point(x, (int)uppery); textrenderer.drawtext(graphics, text, font, point, color, textformatflags.nopadding); }
one thing forgot mention: tried textformatflags
set bottom
. problem descending letters causing text above line.
is there easier way or how can remove padding?
the link in donald's comment pointing dar7yl's excellent answer right.
all kudos dar7yl! below example , result, nicely lined on same line:
private void form1_load(object sender, eventargs e) { using (graphics g = panel2.creategraphics() ) { fonts.add(new drawfont(g, new fontfamily("arial"), 7f)); fonts.add(new drawfont(g, new fontfamily("arial"), 12f)); fonts.add(new drawfont(g, new fontfamily("arial"), 17f)); fonts.add(new drawfont(g, new fontfamily("consolas"), 8f)); fonts.add(new drawfont(g, new fontfamily("consolas"), 10f)); fonts.add(new drawfont(g, new fontfamily("consolas"), 14f)); fonts.add(new drawfont(g, new fontfamily("times"), 9f)); fonts.add(new drawfont(g, new fontfamily("times"), 12f)); fonts.add(new drawfont(g, new fontfamily("times"), 20f)); fonts.add(new drawfont(g, new fontfamily("segoe print"), 6f)); fonts.add(new drawfont(g, new fontfamily("segoe print"), 12f)); fonts.add(new drawfont(g, new fontfamily("segoe print"), 24f)); } } list<drawfont> fonts = new list<drawfont>(); class drawfont { public font font { get; set; } public float baseline { get; set; } public drawfont(graphics g, fontfamily ff, float height, fontstyle style) { font = new font(ff, height, style); float linespace = ff.getlinespacing(font.style); float ascent = ff.getcellascent(font.style); baseline = font.getheight(g) * ascent / linespace; } } private void panel2_paint(object sender, painteventargs e) { float x = 5f; foreach ( drawfont font in fonts ) { e.graphics.drawstring("fy", font.font, brushes.darkslateblue, x, 80 - font.baseline); x += 50; } e.graphics.drawline(pens.lightslategray, 0, 80, 999, 80); }
i use graphics.drawstring
, textrenderer
should work well..
Comments
Post a Comment