elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.


Tema destacado: Estamos en la red social de Mastodon


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
0 Usuarios y 2 Visitantes están viendo este tema.
Páginas: 1 ... 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 [62] Ir Abajo Respuesta Imprimir
Autor Tema: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)  (Leído 625,484 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.980



Ver Perfil
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #610 en: 9 Diciembre 2025, 09:16 am »

Un simple TypeConverter junto a un UITypeEditor (opcional) para representar un color en formato web.



Nota: los colores no se ven como deberían por la compresión de imagen del software que he usado para capturar el GIF animado xD

WebColorConverter.vb
Código
  1. #Region " Option Statements "
  2.  
  3. Option Strict On
  4. Option Explicit On
  5. Option Infer Off
  6.  
  7. #End Region
  8.  
  9. #Region " Imports "
  10.  
  11. Imports System.ComponentModel
  12. Imports System.Globalization
  13.  
  14. #End Region
  15.  
  16. Public Class WebColorConverter : Inherits ColorConverter
  17.  
  18.    <DebuggerStepThrough>
  19.    Public Overrides Function GetStandardValuesSupported(context As ITypeDescriptorContext) As Boolean
  20.  
  21.        Return True
  22.    End Function
  23.  
  24.    <DebuggerStepThrough>
  25.    Public Overrides Function GetStandardValues(context As ITypeDescriptorContext) As StandardValuesCollection
  26.  
  27.        Dim collection As New Collection()
  28.  
  29.        For Each kc As KnownColor In [Enum].GetValues(GetType(KnownColor))
  30.            Dim color As Color = Color.FromKnownColor(kc)
  31.  
  32.            If Not color.IsSystemColor AndAlso color.IsNamedColor Then
  33.                collection.Add(color)
  34.            End If
  35.        Next
  36.  
  37.        Return New StandardValuesCollection(collection)
  38.    End Function
  39.  
  40.    <DebuggerStepThrough>
  41.    Public Overrides Function ConvertTo(context As ITypeDescriptorContext,
  42.                                    culture As CultureInfo,
  43.                                    value As Object,
  44.                                    destinationType As Type) As Object
  45.  
  46.        If destinationType Is GetType(String) AndAlso TypeOf value Is Color Then
  47.            Dim color As Color = DirectCast(value, Color)
  48.            Dim html As String = If(color.A <> 255, $"#{color.A:X2}{color.R:X2}{color.G:X2}{color.B:X2}",
  49.                                    ColorTranslator.ToHtml(Color.FromArgb(color.R, color.G, color.B)))
  50.  
  51.            Dim name As String = Nothing
  52.            For Each knownColor As KnownColor In [Enum].GetValues(GetType(KnownColor))
  53.                Dim k As Color = Color.FromKnownColor(knownColor)
  54.                If k.A = color.A AndAlso
  55.                   k.R = color.R AndAlso
  56.                   k.G = color.G AndAlso
  57.                   k.B = color.B AndAlso Not k.IsSystemColor Then
  58.  
  59.                    name = k.Name
  60.                    Exit For
  61.                End If
  62.            Next
  63.  
  64.            Return If(name IsNot Nothing, $"{html} ({name})", html)
  65.        End If
  66.  
  67.        Return MyBase.ConvertTo(context, culture, value, destinationType)
  68.    End Function
  69.  
  70.    <DebuggerStepThrough>
  71.    Public Overrides Function ConvertFrom(context As ITypeDescriptorContext,
  72.                                          culture As CultureInfo,
  73.                                          value As Object) As Object
  74.  
  75.        Dim s As String = TryCast(value, String)
  76.        If s IsNot Nothing Then
  77.            s = s.Trim()
  78.  
  79.            ' If input is like "xxx (Name)" remove the part in parentheses
  80.            Dim idx As Integer = s.IndexOf("("c)
  81.            If idx >= 0 Then
  82.                s = s.Substring(0, idx).Trim()
  83.            End If
  84.  
  85.            If s.StartsWith("#") Then
  86.                Dim hx As String = s.Substring(1).Trim()
  87.  
  88.                ' Support #RRGGBB and #AARRGGBB
  89.                If hx.Length = 6 Then
  90.                    Dim r As Integer = Convert.ToInt32(hx.Substring(0, 2), 16)
  91.                    Dim g As Integer = Convert.ToInt32(hx.Substring(2, 2), 16)
  92.                    Dim b As Integer = Convert.ToInt32(hx.Substring(4, 2), 16)
  93.                    Return Color.FromArgb(255, r, g, b)
  94.  
  95.                ElseIf hx.Length = 8 Then
  96.                    Dim a As Integer = Convert.ToInt32(hx.Substring(0, 2), 16)
  97.                    Dim r As Integer = Convert.ToInt32(hx.Substring(2, 2), 16)
  98.                    Dim g As Integer = Convert.ToInt32(hx.Substring(4, 2), 16)
  99.                    Dim b As Integer = Convert.ToInt32(hx.Substring(6, 2), 16)
  100.                    Return Color.FromArgb(a, r, g, b)
  101.  
  102.                Else
  103.                    ' Support short hex format (#RGB) by expanding to 6 digits
  104.                    If hx.Length = 3 Then
  105.                        Dim r As Integer = Convert.ToInt32(String.Concat(hx(0), hx(0)), 16)
  106.                        Dim g As Integer = Convert.ToInt32(String.Concat(hx(1), hx(1)), 16)
  107.                        Dim b As Integer = Convert.ToInt32(String.Concat(hx(2), hx(2)), 16)
  108.                        Return Color.FromArgb(255, r, g, b)
  109.                    End If
  110.                End If
  111.  
  112.            Else
  113.                ' Try ColorTranslator for standard names and "Transparent"
  114.                Try
  115.                    Dim c As Color = ColorTranslator.FromHtml(s)
  116.                    ' ColorTranslator.FromHtml returns A=255 for known names; A=0 for "Transparent"
  117.                    Return c
  118.  
  119.                Catch ex As Exception
  120.                    ' Try KnownColor enum (e.g. user types "White" or "WhiteSmoke")
  121.                    Try
  122.                        Dim kc As KnownColor
  123.                        If [Enum].TryParse(s, True, kc) Then
  124.                            Return Color.FromKnownColor(kc)
  125.                        End If
  126.                    Catch
  127.                        ' Continue to fallback
  128.                    End Try
  129.                End Try
  130.            End If
  131.  
  132.            ' If everything fails, fallback to the base converter (throws or defaults)
  133.        End If
  134.  
  135.        Return MyBase.ConvertFrom(context, culture, value)
  136.    End Function
  137.  
  138. End Class
  139.  

WebColorEditor.vb
Código
  1. #Region " Option Statements "
  2.  
  3. Option Strict On
  4. Option Explicit On
  5. Option Infer Off
  6.  
  7. #End Region
  8.  
  9. #Region " Imports "
  10.  
  11. Imports System.ComponentModel
  12. Imports System.Drawing.Design
  13.  
  14. #End Region
  15.  
  16. Public Class WebColorEditor : Inherits UITypeEditor
  17.  
  18.    <DebuggerStepThrough>
  19.    Public Overrides Function GetEditStyle(context As ITypeDescriptorContext) As UITypeEditorEditStyle
  20.  
  21.        Return UITypeEditorEditStyle.None
  22.    End Function
  23.  
  24.    <DebuggerStepThrough>
  25.    Public Overrides Function GetPaintValueSupported(context As ITypeDescriptorContext) As Boolean
  26.  
  27.        Return True
  28.    End Function
  29.  
  30.    <DebuggerStepThrough>
  31.    Public Overrides Sub PaintValue(e As PaintValueEventArgs)
  32.  
  33.        Dim color As Color
  34.  
  35.        If TypeOf e.Value Is Color Then
  36.            color = DirectCast(e.Value, Color)
  37.        Else
  38.            Exit Sub
  39.        End If
  40.  
  41.        Using brush As New SolidBrush(color)
  42.            e.Graphics.FillRectangle(brush, e.Bounds)
  43.        End Using
  44.    End Sub
  45.  
  46. End Class

Modo de empleo:
Código
  1. Imports System.ComponentModel
  2. Imports System.Drawing.Design
  3.  
  4. Public Class Form1
  5.  
  6.    Private ReadOnly ClassTest As New MyClassTest
  7.  
  8.    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  9.  
  10.        Me.PropertyGrid1.SelectedObject = Me.ClassTest
  11.    End Sub
  12.  
  13.    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
  14.  
  15.        Me.ClassTest.MyColor = Color.FromArgb(255, 116, 222, 4)
  16.        Me.PropertyGrid1.Refresh()
  17.    End Sub
  18. End Class
  19.  
  20. Friend NotInheritable Class MyClassTest
  21.  
  22.    <TypeConverter(GetType(WebColorConverter))>
  23.    <Editor(GetType(WebColorEditor), GetType(UITypeEditor))> ' El editor es opcional.
  24.    Public Property MyColor As Color = Color.Transparent
  25.  
  26. End Class

Ejemplo de utilidad en la vida real: un programa open-source para mostrar en tiempo real el color del pixel actual en la pantalla (entre otras cosas):



« Última modificación: 9 Diciembre 2025, 09:30 am por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.980



Ver Perfil
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #611 en: 11 Diciembre 2025, 16:42 pm »

Un par de funciones auxiliares relacionadas con la colorimetría...

Calcula el color promedio de un área rectangular especificada dentro de un Bitmap:
Código
  1. ''' <summary>
  2. ''' Calculates the average color of a specified rectangular area within a <see cref="Bitmap"/>.
  3. ''' </summary>
  4. '''
  5. ''' <param name="bmp">
  6. ''' The <see cref="Bitmap"/> from which to sample colors.
  7. ''' </param>
  8. '''
  9. ''' <param name="rectF">
  10. ''' The rectangular area (<see cref="RectangleF"/>) to sample.
  11. ''' <para></para>
  12. ''' The rectangle is automatically clamped to the bitmap bounds.
  13. ''' </param>
  14. '''
  15. ''' <param name="background">
  16. ''' Optional background color for compositing.
  17. ''' <para></para>
  18. ''' If not provided or <see cref="Color.Empty"/>, <see cref="Color.Black"/> is assumed.
  19. ''' </param>
  20. '''
  21. ''' <returns>
  22. ''' A <see cref="Color"/> representing the average ARGB color of all pixels in the specified area.
  23. ''' <para></para>
  24. ''' If the rectangle is empty or outside the bitmap, returns <see cref="Color.Black"/>.
  25. ''' </returns>
  26. <DebuggerStepThrough>
  27. Public Shared Function GetAverageColor(bmp As Bitmap, rectF As RectangleF,
  28.                                       Optional background As Color = Nothing) As Color
  29.  
  30.    Dim rect As Rectangle = Rectangle.Intersect(Rectangle.Round(rectF), New Rectangle(0, 0, bmp.Width, bmp.Height))
  31.    If rect.Width <= 0 OrElse rect.Height <= 0 Then
  32.        Return Color.Black
  33.    End If
  34.  
  35.    Dim bgColor As Color = If(background = Color.Empty, Color.Black, background)
  36.  
  37.    Dim aSum As Double
  38.    Dim rSum As Double
  39.    Dim gSum As Double
  40.    Dim bSum As Double = 0
  41.    Dim count As Integer = rect.Width * rect.Height
  42.  
  43.    ' Lock the bitmap for direct memory access
  44.    Dim bmpData As BitmapData = bmp.LockBits(rect, ImageLockMode.ReadOnly, bmp.PixelFormat)
  45.    Dim bytesPerPixel As Integer = Image.GetPixelFormatSize(bmp.PixelFormat) \ 8
  46.    Dim stride As Integer = bmpData.Stride
  47.    Dim scan0 As IntPtr = bmpData.Scan0
  48.  
  49.    Dim buffer((stride * rect.Height) - 1) As Byte
  50.    Marshal.Copy(scan0, buffer, 0, buffer.Length)
  51.  
  52.    For y As Integer = 0 To rect.Height - 1
  53.        For x As Integer = 0 To rect.Width - 1
  54.            Dim i As Integer = y * stride + x * bytesPerPixel
  55.            Dim b As Byte = buffer(i)
  56.            Dim g As Byte = buffer(i + 1)
  57.            Dim r As Byte = buffer(i + 2)
  58.            Dim a As Byte = If(bytesPerPixel >= 4, buffer(i + 3), CByte(255))
  59.  
  60.            Dim alphaFactor As Double = a / 255.0
  61.            rSum += r * alphaFactor + bgColor.R * (1 - alphaFactor)
  62.            gSum += g * alphaFactor + bgColor.G * (1 - alphaFactor)
  63.            bSum += b * alphaFactor + bgColor.B * (1 - alphaFactor)
  64.            aSum += a
  65.        Next
  66.    Next
  67.  
  68.    bmp.UnlockBits(bmpData)
  69.  
  70.    Dim avgA As Integer = CInt(aSum / count)
  71.    Dim avgR As Integer = CInt(rSum / count)
  72.    Dim avgG As Integer = CInt(gSum / count)
  73.    Dim avgB As Integer = CInt(bSum / count)
  74.  
  75.    Return Color.FromArgb(avgA, avgR, avgG, avgB)
  76. End Function

Calcula la luminancia percibida de un color, opcionalmente compuesta sobre un color de fondo:
Código
  1. ''' <summary>
  2. ''' Calculates the perceived luminance of a color, optionally composited over a background color.
  3. ''' </summary>
  4. '''
  5. ''' <param name="color">
  6. ''' The color whose luminance is to be calculated. Includes alpha channel.
  7. ''' </param>
  8. '''
  9. ''' <param name="background">
  10. ''' Optional background color for compositing.
  11. ''' <para></para>
  12. ''' If not provided or <see cref="Color.Empty"/>, <see cref="Color.Black"/> is assumed.
  13. ''' </param>
  14. '''
  15. ''' <returns>
  16. ''' A <see cref="Double"/> representing the relative luminance of the color in the range 0.0 (black) to 1.0 (white).
  17. ''' </returns>
  18. <DebuggerStepThrough>
  19. Public Shared Function GetLuminance(color As Color, Optional background As Color = Nothing) As Double
  20.  
  21.    Dim bgColor As Color = If(background = Color.Empty, Color.Black, background)
  22.  
  23.    Dim alpha As Double = color.A / 255.0
  24.    Dim r As Double = color.R * alpha + bgColor.R * (1 - alpha)
  25.    Dim g As Double = color.G * alpha + bgColor.G * (1 - alpha)
  26.    Dim b As Double = color.B * alpha + bgColor.B * (1 - alpha)
  27.  
  28.    ' Standard luma weighting associated with Rec. 601 when deriving brightness from RGB.
  29.    ' Y'601 = 0.299 R' + 0.587 G' + 0.114 B'.
  30.    ' https://en.wikipedia.org/wiki/Rec._601
  31.    ' https://gmao.gsfc.nasa.gov/media/gmaoftp/jkolassa/Matlab_scripts/colorspace.html
  32.    Dim luminance As Double = (0.299 * r +
  33.                               0.587 * g +
  34.                               0.114 * b
  35.                              ) / 255.0
  36.  
  37.    Return luminance
  38. End Function


En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.980



Ver Perfil
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #612 en: 11 Diciembre 2025, 16:49 pm »

Una forma universal y personalizable para reportar progreso en nuestro icono del área de notificación (system tray)...

Importante: recomiendo no usar más de dos caracteres para el texto. Con tres caracteres ya se achica mucho, y con más, se vuelve prácticamente imposible de leer. Hay muy poco espacio legible para un icono de 32x32px.

                   

NotifyIconProgressBar.vb
Código
  1. Public Structure NotifyIconProgressBar
  2.  
  3.    Public Height As Integer
  4.    Public BackColor As Color
  5.    Public ForeColor As Color
  6.    Public FillColor As Color
  7.    Public BorderColor As Color
  8.    Public BorderWidth As Integer
  9.  
  10.    Public Shared ReadOnly Property Empty As NotifyIconProgressBar
  11.        Get
  12.            Return New NotifyIconProgressBar With {
  13.                .Height = 0,
  14.                .BackColor = Color.Empty,
  15.                .ForeColor = Color.Empty,
  16.                .FillColor = Color.Empty,
  17.                .BorderColor = Color.Empty,
  18.                .BorderWidth = 0
  19.            }
  20.        End Get
  21.    End Property
  22.  
  23. End Structure

P/invokes:
Código
  1. <DllImport("user32.dll", SetLastError:=True)>
  2. Private Shared Function DestroyIcon(hIcon As IntPtr) As Boolean
  3. End Function

El método principal:
Código
  1. Imports System.Drawing.Drawing2D
  2. Imports System.Drawing.Text
  3. Imports System.Runtime.InteropServices
  4.  
  5. ''' <summary>
  6. ''' Renders a progress bar overlay on a <see cref="NotifyIcon"/> and optionally draws text on it.
  7. ''' </summary>
  8. '''
  9. ''' <param name="ntfy">
  10. ''' The <see cref="NotifyIcon"/> whose icon will be updated with the rendered progress bar.
  11. ''' </param>
  12. '''
  13. ''' <param name="progressBar">
  14. ''' A <see cref="NotifyIconProgressBar"/> structure containing the bar's height, colors and border width.
  15. ''' </param>
  16. '''
  17. ''' <param name="value">
  18. ''' The current position of the progress bar.
  19. ''' </param>
  20. '''
  21. ''' <param name="maximumValue">
  22. ''' The maximum <paramref name="value"/> range of the progress bar.
  23. ''' </param>
  24. '''
  25. ''' <param name="text">
  26. ''' Optional text to display centered above the progress bar.
  27. ''' Must be 3 characters or fewer if provided.
  28. ''' </param>
  29. <DebuggerStepThrough>
  30. Public Shared Sub RenderNotifyIconProgressBar(ntfy As NotifyIcon, baseIcon As Icon, progressBar As NotifyIconProgressBar,
  31.                                              value As Integer, maximumValue As Integer,
  32.                                              Optional text As String = Nothing)
  33.  
  34.    If ntfy Is Nothing Then
  35.        Throw New ArgumentNullException(NameOf(ntfy))
  36.    End If
  37.  
  38.    If baseIcon Is Nothing Then
  39.        Throw New ArgumentNullException(NameOf(baseIcon))
  40.    End If
  41.  
  42.    If maximumValue <= 0 Then
  43.        Throw New ArgumentOutOfRangeException(NameOf(maximumValue), $"{NameOf(maximumValue)} must be greater than zero.")
  44.    End If
  45.  
  46.    If value < 0 OrElse (value > maximumValue) Then
  47.        Throw New ArgumentOutOfRangeException(NameOf(value), $"{NameOf(value)} must be between zero and {NameOf(maximumValue)}.")
  48.    End If
  49.  
  50.    Dim currentIcon As Icon = ntfy.Icon
  51.  
  52.    Using bmp As Bitmap = baseIcon.ToBitmap()
  53.  
  54.        Dim width As Integer = bmp.Width
  55.        Dim height As Integer = bmp.Height
  56.  
  57.        If progressBar.Height <= 0 Then
  58.            Throw New ArgumentOutOfRangeException(NameOf(progressBar.Height), $"{NameOf(progressBar.Height)} must be greater than zero.")
  59.        End If
  60.  
  61.        If progressBar.Height > height Then
  62.            Throw New ArgumentOutOfRangeException(NameOf(progressBar.Height), $"{NameOf(progressBar.Height)} ({progressBar.Height}) exceeds the icon height ({height}).")
  63.        End If
  64.  
  65.        If progressBar.BorderWidth > height Then
  66.            Throw New ArgumentOutOfRangeException(NameOf(progressBar.BorderWidth), $"{NameOf(progressBar.BorderWidth)} ({progressBar.BorderWidth}) exceeds the icon height ({height}).")
  67.        End If
  68.  
  69.        Using g As Graphics = Graphics.FromImage(bmp)
  70.            g.CompositingMode = CompositingMode.SourceOver
  71.            g.CompositingQuality = CompositingQuality.HighQuality
  72.            g.InterpolationMode = InterpolationMode.High
  73.            g.PixelOffsetMode = PixelOffsetMode.Half
  74.            g.SmoothingMode = SmoothingMode.AntiAlias
  75.            g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit
  76.  
  77.            Dim barY As Integer = height - progressBar.Height
  78.  
  79.            Using backgroundBrush As New SolidBrush(progressBar.BackColor)
  80.                g.FillRectangle(backgroundBrush, 0, barY, width, progressBar.Height)
  81.            End Using
  82.  
  83.            Using fillBrush As New SolidBrush(progressBar.FillColor)
  84.                Dim percent As Single = CSng(value / maximumValue)
  85.                Dim filledWidth As Integer = CInt(width * percent)
  86.                g.FillRectangle(fillBrush, 0, barY, filledWidth, progressBar.Height)
  87.            End Using
  88.  
  89.            If progressBar.BorderWidth > 0 Then
  90.                Using borderPen As New Pen(progressBar.BorderColor, progressBar.BorderWidth)
  91.                    g.DrawRectangle(borderPen, 0, barY, width - 1, progressBar.Height)
  92.                End Using
  93.            End If
  94.  
  95.            If Not String.IsNullOrWhiteSpace(text) Then
  96.  
  97.                Using fontFamily As New FontFamily("Segoe UI")
  98.                    Dim fontStyle As FontStyle = FontStyle.Bold
  99.  
  100.                    Dim layoutRect As New RectangleF(0, 0, width, height)
  101.                    Dim fontSizePx As Single = ComputeMaxFontSizeForRectangle(g, text, fontFamily, fontStyle, layoutRect)
  102.  
  103.                    Using font As New Font(fontFamily, fontSizePx, fontStyle, GraphicsUnit.Pixel)
  104.  
  105.                        Using gp As New GraphicsPath()
  106.                            Dim sf As New StringFormat() With {
  107.                                .Alignment = StringAlignment.Center,
  108.                                .LineAlignment = StringAlignment.Center
  109.                            }
  110.                            gp.AddString(text, font.FontFamily, font.Style, font.Size, layoutRect, sf)
  111.  
  112.                            ' Outline then fill for best legibility
  113.                            Using outlinePen As New Pen(Color.FromArgb(220, Color.Black), Math.Max(1.0F, fontSizePx * 0.18F))
  114.                                outlinePen.LineJoin = LineJoin.Round
  115.                                g.DrawPath(outlinePen, gp)
  116.                            End Using
  117.  
  118.                            Using foregroundBrush As New SolidBrush(progressBar.ForeColor)
  119.                                g.FillPath(foregroundBrush, gp)
  120.                            End Using
  121.                        End Using
  122.                    End Using
  123.                End Using
  124.            End If
  125.        End Using
  126.  
  127.        Dim hIcon As IntPtr = bmp.GetHicon()
  128.        Using tempIcon As Icon = Icon.FromHandle(hIcon)
  129.            Dim finalIcon As Icon = CType(tempIcon.Clone(), Icon)
  130.            DestroyIcon(hIcon)
  131.            ntfy.Icon = finalIcon
  132.        End Using
  133.  
  134.        currentIcon.Dispose()
  135.    End Using
  136. End Sub

Función auxiliar necesaria:
Código
  1. ''' <summary>
  2. ''' Determines the largest font size that allows the specified text to fit entirely
  3. ''' within the given rectangle when drawn using the provided <see cref="Graphics"/> object.
  4. ''' </summary>
  5. '''
  6. ''' <param name="g">
  7. ''' The source <see cref="Graphics"/> object used to measure the text.
  8. ''' </param>
  9. '''
  10. ''' <param name="text">
  11. ''' The text to measure.
  12. ''' </param>
  13. '''
  14. ''' <param name="fontFamily">
  15. ''' The font family to use (e.g., "Segoe UI").
  16. ''' </param>
  17. '''
  18. ''' <param name="fontStyle">
  19. ''' The font style (e.g., <see cref="FontStyle.Regular"/>).
  20. ''' </param>
  21. '''
  22. ''' <param name="layoutRectangle">
  23. ''' The rectangle within which the text must fit.
  24. ''' </param>
  25. '''
  26. ''' <param name="minimumSize">
  27. ''' The minimum allowed font size (in <see cref="GraphicsUnit.Pixel"/>).
  28. ''' <para></para>
  29. ''' If the text does not fit even at this size, the function returns this value.
  30. ''' <para></para>
  31. ''' Default value is <c>1.0</c>.
  32. ''' </param>
  33. '''
  34. ''' <param name="tolerance">
  35. ''' The precision threshold for how closely the function tries to fit the text in the rectangle, in <see cref="GraphicsUnit.Pixel"/>.
  36. ''' <para></para>
  37. ''' Smaller values gives more exact results but will require more time to compute.
  38. ''' <para></para>
  39. ''' Default value is <c>0.5</c>.
  40. ''' </param>
  41. '''
  42. ''' <returns>
  43. ''' The largest font size in <see cref="GraphicsUnit.Pixel"/> that fits the text inside the rectangle.
  44. ''' <para></para>
  45. ''' If the text cannot fit even at <paramref name="minimumSize"/>, that minimum value is returned.
  46. ''' </returns>
  47. Public Shared Function ComputeMaxFontSizeForRectangle(g As Graphics, text As String,
  48.                                                      fontFamily As FontFamily, fontStyle As FontStyle,
  49.                                                      layoutRectangle As RectangleF,
  50.                                                      Optional minimumSize As Single = 1.0F,
  51.                                                      Optional tolerance As Single = 0.5F) As Single
  52.  
  53.    Dim minSize As Single = minimumSize
  54.    Dim maxSize As Single = layoutRectangle.Height
  55.    Dim bestFit As Single = minSize
  56.  
  57.    While (maxSize - minSize) > tolerance
  58.        Dim midSize As Single = (minSize + maxSize) / 2
  59.  
  60.        Using testFont As New Font(fontFamily, midSize, fontStyle, GraphicsUnit.Pixel)
  61.            Dim textSize As SizeF = g.MeasureString(text, testFont)
  62.  
  63.            If (textSize.Width <= layoutRectangle.Width) AndAlso
  64.               (textSize.Height <= layoutRectangle.Height) Then
  65.                bestFit = midSize
  66.                minSize = midSize
  67.            Else
  68.                maxSize = midSize
  69.            End If
  70.        End Using
  71.    End While
  72.  
  73.    Return Math.Max(minimumSize, bestFit)
  74. End Function

Ejemplo de uso:
Código
  1. Private Async Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  2.  
  3.    Dim progressBar As New NotifyIconProgressBar With {
  4.        .Height = 32,
  5.        .BackColor = Color.Transparent,
  6.        .ForeColor = Color.White,
  7.        .FillColor = Color.LimeGreen
  8.    }
  9.  
  10.    Dim ntfy As NotifyIcon = Me.NotifyIcon1
  11.    Dim baseIcon As Icon = DirectCast(ntfy.Icon.Clone(), Icon)
  12.  
  13.    Dim maxValue As Integer = 100
  14.    For i As Integer = 0 To maxValue
  15.        RenderNotifyIconProgressBar(ntfy, baseIcon, progressBar, i, maxValue, CStr(i))
  16.        Await Task.Delay(100)
  17.    Next
  18. End Sub
« Última modificación: 11 Diciembre 2025, 18:17 pm por Eleкtro » En línea



Páginas: 1 ... 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 [62] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines