How to know how many "black" pixels you have in a letter x, using an x font?

Asked

Viewed 233 times

1

The question already says it all, in the way I was doing, I wrote several characters, printed and put the program to tell from one to one :/

  • there is a Drawstring() method in the Graphics class that can be used to draw text.

2 answers

3


Icarus, I developed the following solution based on a Bitmap where a text is written in black pixels and soon after a scan is made on the same image counting the black and white pixels.

Follows the code:

//Instanciação do Bitmap (por padrão todos os pixels são brancos)
var bmp = new Bitmap(100, 100);

//Instanciação da fonte para impressão do(s) caracter(es) no Bitmap
var fonte = new Font(FontFamily.GenericSerif, 24);

//Um novo objeto do tipo Graphics é gerado a partir do Bitmap
var g = Graphics.FromImage(bmp);
//Logo após imprimimos o texto através do objeto Graphics 
g.DrawString("X", fonte, new SolidBrush(Color.Black), 0, 0);
//Que por sua vez ao chamar Flush() grava os dados no Bitmap original.
g.Flush();

int count_black = 0, count_white = 0;

//Efetuamos a varredura pixel a pixel no Bitmap e verificamos quais pixels são brancos ou pretos e incrementamos o contador.
for (int x = 0; x < bmp.Width; ++x)
{
    for (int y = 0; y < bmp.Height; ++y)
    {
        var pxl_color = bmp.GetPixel(x, y).ToArgb();

        if (pxl_color == Color.Black.ToArgb()) ++count_black; 
        else ++count_white;
    }
}

//Mostramos o resultado da varredura.
MessageBox.Show(count_black.ToString() + " pixels pretos e " + count_white.ToString() + " pixels brancos foram encontrados.");

Code tested in Windows Forms project.

  • 1

    Note that I incremented the white pixel counter in "Else" because I knew previously that there were no pixels of other colors in Bitmap.

  • CARAAAA VOCE IS A DEEUUSSS!!! EXACTLY WHAT I WANTED ::o:o:o:o:o:o:o:o:o

2

The question does not say exactly everything. You mention the font of the letter, so I imagined that your need involves knowing the dimensions of a text to do something about, and not necessarily count the pixels in the text. But I could be wrong. If your need is to actually count the pixels, the answer from fellow @Brunobermann is the way (and has also that other question which may be useful). Otherwise, what you need is to use the source metrics (with the help of the method Graphics.MeasureString).

Here’s an example (based on the example in the documentation) that calculates the dimensions of the text just to draw a red rectangle around it:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TesteSOPT
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            // Cria a string a ser desenhada
            String drawString = "Olá Mundo!";

            // Cria a fonte e o brush de pintura
            Font drawFont = new Font("Arial", 42);
            SolidBrush drawBrush = new SolidBrush(Color.Black);

            // Esse é o ponto a partir de onde o texto vai ser pintado (canto esquerdo-superior).
            Point drawPoint = new Point(10, 20);

            // Pinta o texto na janela (Form1).
            e.Graphics.DrawString(drawString, drawFont, drawBrush, drawPoint);

            // Desenha um retângulo vermelho ao redor do texto, usando as métricas de fonte
            rectAround(drawPoint, drawFont, drawString, e.Graphics);

        }

        private void rectAround(Point drawPoint, Font drawFont, string drawString, Graphics g  )
        {
            Size textSize = g.MeasureString(drawString, drawFont).ToSize();
            Console.WriteLine(textSize);

            Pen pen = new Pen(new SolidBrush(Color.Red), 5);
            Rectangle rect = new Rectangle(drawPoint, textSize);

            g.DrawRectangle(pen, rect);
        }
    }
}

This code produces the following output:

inserir a descrição da imagem aqui

  • Very good, but the friend there did exactly what I wanted the/!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.