How do I get the pixel dimensions of a string?

Source: Internet
Author: User
Tags drawtext truncated
String CSDN the entire contents of the new home page are currently manually updated, the workload is very large, one reason is to reduce the title of the article, so that there is no longer line of the situation.

Can be in the program to control the width of the title, more than the words automatically truncated and tooltip form to display the full title, but because the CSDN home font is Tahoma 12px, the English font is not equal width, it is difficult to determine the width.

has been no use to solve the problem, yesterday, about the page maintenance workload too big comments were proposed, so some sections of the content is bound to need automatic Updates, so the title needs to be automatically truncated.

So I need to get the size of the string, pixel units.

In the System.Drawing space of. NET, the Graphics object provides a way to do this: MeasureString (), whose overload information is available in MSDN.

Experiment last night. The code snippet that gets the length of the string is as follows:
private void Mainform_paint (object sender, System.Windows.Forms.PaintEventArgs e) {font font = new Font ("Tahoma", Grap Hicsunit.pixel); SizeF size = e.graphics.measurestring (drawText, font); This. Text = size. Width.tostring (); E.graphics.drawrectangle (New Pen (color.red, 1), 0.0F, 0.0F, size. Width, size. Height); E.graphics.drawstring (DrawText, Font, Brushes.black, new PointF (0, 0));


The width pixel value obtained at present is slightly greater than the theoretical value. Tomorrow continue to perfect the ~



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.