How to Convert a String Length to a Pixel Unit

How can I convert a string length to a pixel unit?

Without using of a control or form:

using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(new Bitmap(1, 1)))
{
SizeF size = graphics.MeasureString("Hello there", new Font("Segoe UI", 11, FontStyle.Regular, GraphicsUnit.Point));
}

Or in VB.Net:

Using graphics As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(New Bitmap(1, 1))
Dim size As SizeF = graphics.MeasureString("Hello there", New Font("Segoe UI", 11, FontStyle.Regular, GraphicsUnit.Point))
End Using

How to find string's width in C# (in pixels)

Use Graphics.MeasureString()

From MSDN: http://msdn.microsoft.com/en-us/library/6xe5hazb.aspx

private void MeasureStringMin(PaintEventArgs e)
{
// Set up string.
string measureString = "Measure String";
Font stringFont = new Font("Arial", 16);

// Measure string.
SizeF stringSize = new SizeF();
stringSize = e.Graphics.MeasureString(measureString, stringFont);

// Draw rectangle representing size of string.
e.Graphics.DrawRectangle(new Pen(Color.Red, 1), 0.0F, 0.0F, stringSize.Width, stringSize.Height);

// Draw string to screen.
e.Graphics.DrawString(measureString, stringFont, Brushes.Black, new PointF(0, 0));
}

String length in pixels in Java

that does not use any GUI components?

It depends on what you mean here. I'm assuming you mean you want to do it without receiving a HeadlessException.

The best way is with a BufferedImage. AFAIK, this won't throw a HeadlessException:

Font font = ... ;
BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
FontMetrics fm = img.getGraphics().getFontMetrics(font);
int width = fm.stringWidth("Your string");

Other than using something like this, I don't think you can. You need a graphics context in order to create a FontMetrics and give you font size information.

How do you calculate pixel size of string?

I think you need to create a textblock in code and assign the desired text to it. Then you can get the actual height and width from it. See the below code

         TextBlock txt=new TextBlock();
//set additional properties of textblock here . Such as font size,font family, width etc.
txt.Text = "your text here";
var height = txt.ActualHeight;
var width = txt.ActualWidth;

You can do further operations based on this height and width

I am not saying this is the optimized solution .But this will work for you

String length in pixels flutter

here is sample code:

import 'package:flutter/material.dart';

void main() {
runApp(MaterialApp(home: Scaffold(body: Home())));
}

class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
var text = 'I\'m awesome!';
var size = calcTextSize(text, TextStyle(fontSize: 20));

return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(text, style: TextStyle(fontSize: 20)),
Container(width: size.width, height: 4, color: Colors.blue),
Text(size.width.toString()), // this blue line has exactly same width as text above
],
),
);
}

Size calcTextSize(String text, TextStyle style) {
final TextPainter textPainter = TextPainter(
text: TextSpan(text: text, style: style),
textDirection: TextDirection.ltr,
textScaleFactor: WidgetsBinding.instance.window.textScaleFactor,
)..layout();
return textPainter.size;
}
}

enter image description here

Measuring length of string in pixel in javascript

The simplest solution is to create an in memory canvas (i.e. one that isn't added to the DOM) and then use the measureText function :

var canvas = document.createElement('canvas');
var ctx = canvas.getContext("2d");
ctx.font = "11px Arial";
var width = ctx.measureText(str).width;

Length of a string in pixels

To get a more accurate measurement, you can populate a TextField with the string, then measure the width of that TextField's text.

Code:

function measureString(str:String, format:TextFormat):Rectangle {
var textField:TextField = new TextField();
textField.defaultTextFormat = format;
textField.text = str;

return new Rectangle(0, 0, textField.textWidth, textField.textHeight);
}

Usage:

var format:TextFormat = new TextFormat();
format.font = "Times New Roman";
format.size = 16;

var strings:Array = [ "a", "giraffe", "foo", "!" ];

var calculatedWidth:Number = 50; // Set this to minimum width to start with

for each (var str:String in strings) {
var stringWidth:Number = measureString(str, format).width;
if (stringWidth > calculatedWidth) {
calculatedWidth = stringWidth;
}
}

trace(calculatedWidth);

How to calculate the length (in pixels) of a string in JavaScript?

Given the new information about your wanting to append an ellipsis for text overflow, I think the text-overflow CSS property is a better approach. See this article on quirksmode for more information: http://www.quirksmode.org/css/textoverflow.html

How to calculate length of string in pixels for specific font and size?

An alternative is to ask Windows as follows:

import ctypes

def GetTextDimensions(text, points, font):
class SIZE(ctypes.Structure):
_fields_ = [("cx", ctypes.c_long), ("cy", ctypes.c_long)]

hdc = ctypes.windll.user32.GetDC(0)
hfont = ctypes.windll.gdi32.CreateFontA(points, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, font)
hfont_old = ctypes.windll.gdi32.SelectObject(hdc, hfont)

size = SIZE(0, 0)
ctypes.windll.gdi32.GetTextExtentPoint32A(hdc, text, len(text), ctypes.byref(size))

ctypes.windll.gdi32.SelectObject(hdc, hfont_old)
ctypes.windll.gdi32.DeleteObject(hfont)

return (size.cx, size.cy)

print(GetTextDimensions("Hello world", 12, "Times New Roman"))
print(GetTextDimensions("Hello world", 12, "Arial"))

This would display:

(47, 12)
(45, 12)


Related Topics



Leave a reply



Submit