# C# Bitmap Library to Replace `System.Drawing.Common` in .NET
## IronDrawing é gratuito, de código aberto e suporta a maioria dos formatos de biblioteca de desenho .NET.
**IronDrawing** é uma biblioteca de código aberto originalmente desenvolvida pela Iron Software que ajuda Engenheiros de Software C# a substituir `System.Drawing.Common` em projetos .NET nas plataformas Windows, macOS e Linux.
Desenvolver bibliotecas de classes e pacotes NuGet for .NET 5, 6, 7 e 8 que suportem gráficos, imagens e fontes _deveria_ ser fácil.
O IronDrawing atua como uma ponte perfeita entre todos os novos padrões gráficos propostos para o .NET 5, 6, 7 e 8 à medida que evoluem - assim você só precisa desenvolver para **aquele que preferir** .
<div class="content-img-align-center">
<div class="center-image-wrapper">
<img src="/static-assets/drawing/irondrawing-get-started.webp" alt="IronDrawing é gratuito, de código aberto e suporta a maioria dos formatos de biblioteca de desenho .NET." class="img-responsive add-shadow" width="645" height="618" />
</div>
</div>
<div class="hsg-featured-snippet">
<h2>Etapas técnicas para evitar a exceção "system.drawing.common não é compatível com esta plataforma"</h2>
<ol>
<li>Implement <strong>System.drawing.common</strong> is not possible para .NET 6 and .NET 7 & 8 on Linux and macOS platforms</li>
<li>Usar System.Drawing.Common nessas plataformas resultará em uma mensagem de exceção</li>
<li>Defina a configuração de tempo de execução <strong>System.Drawing.EnableUnixSupport</strong> como <strong>verdadeira</strong> para o .NET 6.</li>
<li>O suporte para System.Drawing.Common não está mais disponível no .NET 7 e 8.</li>
<li>Utilize a biblioteca de código aberto <strong>IronSoftware.Drawing</strong> para substituir <strong>System.Drawing.Common</strong> no .NET 7.</li>
</ol>
</div>
### Contexto
O Microsoft .NET é uma estrutura de software multiplataforma e altamente compatível, utilizada por milhões de desenvolvedores de software em todo o mundo. A Microsoft [anunciou](https://learn.microsoft.com/en-us/dotnet/core/compatibility/core-libraries/6.0/system-drawing-common-windows-only) uma **mudança substancial** na qual `System.Drawing.Common` só será suportada em plataformas Windows.
Isso é problemático para desenvolvedores de bibliotecas .NET que mantêm bibliotecas multiplataforma que usam `System.Drawing.Common` porque a [ação recomendada](https://learn.microsoft.com/en-us/dotnet/core/compatibility/core-libraries/6.0/system-drawing-common-windows-only#recommended-action) da Microsoft exige que você reconstrua sua biblioteca para suportar usuários não-Windows. Espera-se que voluntários e acadêmicos reconstruam todos os pacotes NuGet e bibliotecas de classes para usar **cada uma** das novas bibliotecas gráficas sugeridas à medida que forem surgindo, causando uma dívida técnica que retardará a adoção do .NET moderno.
Em última análise, quando usamos o .NET, usamos o NuGet.
Os desenvolvedores de pacotes NuGet estão nos fazendo um grande favor ao aprimorar o .NET e disponibilizar código pré-empacotado que levaria milhares de horas para escrevermos manualmente todos os dias.
Essa **alteração incompatível com versões anteriores** irá desacelerar o desenvolvimento do NuGet e poderá levar ao abandono ou à obsolescência de bibliotecas de código das quais os desenvolvedores .NET dependem. Precisamos agir agora!
### Nossa solução
Um formato gráfico intermediário que converte entre todas as bibliotecas gráficas antigas e novas.
Como desenvolvedor de bibliotecas de classe, suas Entradas e Saídas públicas `Bitmap`, `Color`, `Rectangle`, `Font`, e `Size` podem ser de apenas um tipo que suporte todos os novos padrões. Internamente, você pode continuar fazendo o que gosta.
**O IronDrawing é compatível com versões anteriores do .NET Framework 4.62 e suporta todas as versões do .NET (incluindo o .NET 8).**
O desenvolvimento e lançamento do IronDrawing resolve esse problema ao fornecer uma solução de código aberto para a falta de um formato uniforme para classes importantes como `Bitmap`, `Color`, `Rectangle`, `Font`, e `Size`. `IronSoftware.Drawing` irá converter perfeitamente entre as implementações desses tipos em `System.Drawing`, `Microsoft.Maui`, `SkiaSharp`, e `SixLabors` para você. Isso permite que você, o desenvolvedor, não precise substituir todas as instâncias dessas classes em sua biblioteca.
Por exemplo, se você estiver usando `System.Drawing.Bitmap`, você pode usar a classe `AnyBitmap` do IronDrawing que tem conversões implícitas para qualquer um desses tipos: `System.Drawing.Bitmap`, `System.Drawing.Image`, `SkiaSharp.SKBitmap`, `SkiaSharp.SKImage`, `SixLabors.ImageSharp`, `Microsoft.Maui.Graphics.Platform.PlatformImage`.
### Por que estamos fazendo isso de graça?
Desenvolvemos o IronDrawing porque nós, da Iron Software, somos desenvolvedores .NET experientes e dedicados, que se preocupam com a evolução do .NET e desejam seu crescimento e sucesso. Adoramos ver que o .NET está crescendo e evoluindo, como podemos ver com o .NET 7. Usamos o NuGet o dia todo, e tenho certeza de que você também. Apoiamos e esperamos incentivar uma transição fácil para o futuro e longe de `System.Drawing`.
Queremos que todo o desenvolvimento de bibliotecas de classes .NET e do NuGet seja mais fácil, para que o ecossistema NuGet continue a prosperar e para que todos os desenvolvedores .NET se beneficiem.
## Recursos `IronSoftware.Drawing`
- **`AnyBitmap`**: Uma classe Bitmap universalmente compatível. Conversão implícita entre `IronSoftware.Drawing.AnyBitmap` e os seguintes suportados:
- `System.Drawing.Bitmap`
- `System.Drawing.Image`
- `SkiaSharp.SKBitmap`
- `SkiaSharp.SKImage`
- `SixLabors.ImageSharp`
- `Microsoft.Maui.Graphics.Platform.PlatformImage`
- **Cor** : Uma classe de cor universalmente compatível. Conversão implícita entre `IronSoftware.Drawing.Color` e os seguintes suportados:
- `System.Drawing.Color`
- `SkiaSharp.SKColor`
- `SixLabors.ImageSharp.Color`
- `SixLabors.ImageSharp.PixelFormats`
- **`Rectangle`**: Uma classe Rectangle universalmente compatível. Conversão implícita entre `IronSoftware.Drawing.Rectangle` e os seguintes suportados:
- `System.Drawing.Rectangle`
- `SkiaSharp.SKRect`
- `SkiaSharp.SKRectI`
- `SixLabors.ImageSharp.Rectangle`
- **Fonte** : Uma classe de fonte universalmente compatível. Conversão implícita entre `IronSoftware.Drawing.Font` e os seguintes suportados:
- `System.Drawing.Font`
- `SkiaSharp.SKFont`
- `SixLabors.Fonts.Font`
### Compatibilidade
**`IronSoftware.Drawing`** tem compatibilidade de suporte multiplataforma com:
- .NET 8, .NET 7, .NET 6, .NET 5, .NET Core, .NET Standard e .NET Framework 4.62+
- Windows, macOS, Linux, Docker, Azure e AWS
## Instalação
Instalar o pacote NuGet IronDrawing (`IronSoftware.Drawing`) é rápido e fácil. Instale o pacote da seguinte forma:
```shell
:InstallCmd Install-Package IronSoftware.System.Drawing
```
Alternativamente, faça o download diretamente do [site oficial do NuGet](https://www.nuget.org/packages/IronSoftware.System.Drawing) .
Uma vez instalado, você pode começar adicionando `using IronSoftware.Drawing;` ao topo do seu código C#.
## Exemplos de código
### Exemplo AnyBitmap
```csharp
:path=/static-assets/drawing/content-code-examples/get-started/anybitmap.cs
```
### Exemplo de cor
```csharp
:path=/static-assets/drawing/content-code-examples/get-started/color.cs
```
### Exemplo de retângulo
```csharp
:path=/static-assets/drawing/content-code-examples/get-started/rectangle.cs
```
### Exemplo de fonte
```csharp
:path=/static-assets/drawing/content-code-examples/get-started/font.cs
```
## Suporte disponível
### Licença
As informações sobre a licença podem ser encontradas aqui: [LICENSE.txt](https://github.com/iron-software/IronSoftware.System.Drawing/blob/master/LICENSE.txt)
### Contribuir
Se você deseja contribuir para o projeto de código aberto IronDrawing, leia a [licença](https://github.com/iron-software/IronSoftware.System.Drawing/blob/master/LICENSE.txt) antes de enviar uma solicitação de pull request para o [repositório no GitHub](https://github.com/iron-software/IronSoftware.System.Drawing) .
### Informação
Para obter mais informações sobre a Iron Software , visite nosso site:[https://ironsoftware.com/](https://ironsoftware.com/)
### Suporte da Iron Software
Para suporte geral e dúvidas técnicas, envie um e-mail para:[support@ironsoftware.com](mailto:support@ironsoftware.com)
IronDrawing é gratuito, de código aberto e suporta a maioria dos formatos de biblioteca de desenho .NET.
IronDrawing é uma biblioteca de código aberto originalmente desenvolvida pela Iron Software que ajuda Engenheiros de Software C# a substituir System.Drawing.Common em projetos .NET nas plataformas Windows, macOS e Linux.
Desenvolver bibliotecas de classes e pacotes NuGet for .NET 5, 6, 7 e 8 que suportem gráficos, imagens e fontes deveria ser fácil.
O IronDrawing atua como uma ponte perfeita entre todos os novos padrões gráficos propostos para o .NET 5, 6, 7 e 8 à medida que evoluem - assim você só precisa desenvolver para aquele que preferir .
Etapas técnicas para evitar a exceção "system.drawing.common não é compatível com esta plataforma"
Implement System.drawing.common is not possible para .NET 6 and .NET 7 & 8 on Linux and macOS platforms
Usar System.Drawing.Common nessas plataformas resultará em uma mensagem de exceção
Defina a configuração de tempo de execução System.Drawing.EnableUnixSupport como verdadeira para o .NET 6.
O suporte para System.Drawing.Common não está mais disponível no .NET 7 e 8.
Utilize a biblioteca de código aberto IronSoftware.Drawing para substituir System.Drawing.Common no .NET 7.
Contexto
O Microsoft .NET é uma estrutura de software multiplataforma e altamente compatível, utilizada por milhões de desenvolvedores de software em todo o mundo. A Microsoft anunciou uma mudança substancial na qual System.Drawing.Common só será suportada em plataformas Windows.
Isso é problemático para desenvolvedores de bibliotecas .NET que mantêm bibliotecas multiplataforma que usam System.Drawing.Common porque a ação recomendada da Microsoft exige que você reconstrua sua biblioteca para suportar usuários não-Windows. Espera-se que voluntários e acadêmicos reconstruam todos os pacotes NuGet e bibliotecas de classes para usar cada uma das novas bibliotecas gráficas sugeridas à medida que forem surgindo, causando uma dívida técnica que retardará a adoção do .NET moderno.
Em última análise, quando usamos o .NET, usamos o NuGet.
Os desenvolvedores de pacotes NuGet estão nos fazendo um grande favor ao aprimorar o .NET e disponibilizar código pré-empacotado que levaria milhares de horas para escrevermos manualmente todos os dias.
Essa alteração incompatível com versões anteriores irá desacelerar o desenvolvimento do NuGet e poderá levar ao abandono ou à obsolescência de bibliotecas de código das quais os desenvolvedores .NET dependem. Precisamos agir agora!
Nossa solução
Um formato gráfico intermediário que converte entre todas as bibliotecas gráficas antigas e novas.
Como desenvolvedor de bibliotecas de classe, suas Entradas e Saídas públicas Bitmap, Color, Rectangle, Font, e Size podem ser de apenas um tipo que suporte todos os novos padrões. Internamente, você pode continuar fazendo o que gosta.
O IronDrawing é compatível com versões anteriores do .NET Framework 4.62 e suporta todas as versões do .NET (incluindo o .NET 8).
O desenvolvimento e lançamento do IronDrawing resolve esse problema ao fornecer uma solução de código aberto para a falta de um formato uniforme para classes importantes como Bitmap, Color, Rectangle, Font, e Size. IronSoftware.Drawing irá converter perfeitamente entre as implementações desses tipos em System.Drawing, Microsoft.Maui, SkiaSharp, e SixLabors para você. Isso permite que você, o desenvolvedor, não precise substituir todas as instâncias dessas classes em sua biblioteca.
Por exemplo, se você estiver usando System.Drawing.Bitmap, você pode usar a classe AnyBitmap do IronDrawing que tem conversões implícitas para qualquer um desses tipos: System.Drawing.Bitmap, System.Drawing.Image, SkiaSharp.SKBitmap, SkiaSharp.SKImage, SixLabors.ImageSharp, Microsoft.Maui.Graphics.Platform.PlatformImage.
Por que estamos fazendo isso de graça?
Desenvolvemos o IronDrawing porque nós, da Iron Software, somos desenvolvedores .NET experientes e dedicados, que se preocupam com a evolução do .NET e desejam seu crescimento e sucesso. Adoramos ver que o .NET está crescendo e evoluindo, como podemos ver com o .NET 7. Usamos o NuGet o dia todo, e tenho certeza de que você também. Apoiamos e esperamos incentivar uma transição fácil para o futuro e longe de System.Drawing.
Queremos que todo o desenvolvimento de bibliotecas de classes .NET e do NuGet seja mais fácil, para que o ecossistema NuGet continue a prosperar e para que todos os desenvolvedores .NET se beneficiem.
Recursos IronSoftware.Drawing
AnyBitmap: Uma classe Bitmap universalmente compatível. Conversão implícita entre IronSoftware.Drawing.AnyBitmap e os seguintes suportados:
System.Drawing.Bitmap
System.Drawing.Image
SkiaSharp.SKBitmap
SkiaSharp.SKImage
SixLabors.ImageSharp
Microsoft.Maui.Graphics.Platform.PlatformImage
Cor : Uma classe de cor universalmente compatível. Conversão implícita entre IronSoftware.Drawing.Color e os seguintes suportados:
System.Drawing.Color
SkiaSharp.SKColor
SixLabors.ImageSharp.Color
SixLabors.ImageSharp.PixelFormats
Rectangle: Uma classe Rectangle universalmente compatível. Conversão implícita entre IronSoftware.Drawing.Rectangle e os seguintes suportados:
System.Drawing.Rectangle
SkiaSharp.SKRect
SkiaSharp.SKRectI
SixLabors.ImageSharp.Rectangle
Fonte : Uma classe de fonte universalmente compatível. Conversão implícita entre IronSoftware.Drawing.Font e os seguintes suportados:
System.Drawing.Font
SkiaSharp.SKFont
SixLabors.Fonts.Font
Compatibilidade
IronSoftware.Drawing tem compatibilidade de suporte multiplataforma com:
.NET 8, .NET 7, .NET 6, .NET 5, .NET Core, .NET Standard e .NET Framework 4.62+
Windows, macOS, Linux, Docker, Azure e AWS
Instalação
Instalar o pacote NuGet IronDrawing (IronSoftware.Drawing) é rápido e fácil. Instale o pacote da seguinte forma:
Uma vez instalado, você pode começar adicionando using IronSoftware.Drawing; ao topo do seu código C#.
Exemplos de código
Exemplo AnyBitmap
using IronSoftware.Drawing;using System.IO;using System.Drawing;// Create a new AnyBitmap object from a file// Replace "FILE_PATH" with the actual path of the image you want to processvar bitmap = AnyBitmap.FromFile("FILE_PATH");// Save the AnyBitmap object as a JPEG filebitmap.SaveAs("result.jpg");// Export the AnyBitmap as a byte array// This can be useful if you want to send the image data over a network or save it in a databasevar bytes = bitmap.ExportBytes();// Create a memory stream to export the AnyBitmap as a JPEG stream with 100% qualityusing (var resultExport = new MemoryStream()){ // This exports the image to the stream with the specified format and quality bitmap.ExportStream(resultExport, AnyBitmap.ImageFormat.Jpeg, 100); // Be sure to use 'using' or manually close the stream to release resources}// Casting between System.Drawing.Bitmap and IronSoftware.Drawing.AnyBitmap// Load a System.Drawing.Bitmap from the same fileSystem.Drawing.Bitmap image = new System.Drawing.Bitmap("FILE_PATH");// This is an implicit conversion from System.Drawing.Bitmap to IronSoftware.Drawing.AnyBitmap// This step is necessary if you are working with System.Drawing.Bitmap and need to convert to IronSoftware.Drawing.AnyBitmap for processingIronSoftware.Drawing.AnyBitmap anyBitmap = AnyBitmap.FromBitmap(image);// Save the resulting AnyBitmap from casting as a PNG fileanyBitmap.SaveAs("result-from-casting.png");
using IronSoftware.Drawing;
using System.IO;
using System.Drawing;
// Create a new AnyBitmap object from a file
// Replace "FILE_PATH" with the actual path of the image you want to process
var bitmap = AnyBitmap.FromFile("FILE_PATH");
// Save the AnyBitmap object as a JPEG file
bitmap.SaveAs("result.jpg");
// Export the AnyBitmap as a byte array
// This can be useful if you want to send the image data over a network or save it in a database
var bytes = bitmap.ExportBytes();
// Create a memory stream to export the AnyBitmap as a JPEG stream with 100% quality
using (var resultExport = new MemoryStream())
{
// This exports the image to the stream with the specified format and quality
bitmap.ExportStream(resultExport, AnyBitmap.ImageFormat.Jpeg, 100);
// Be sure to use 'using' or manually close the stream to release resources
}
// Casting between System.Drawing.Bitmap and IronSoftware.Drawing.AnyBitmap
// Load a System.Drawing.Bitmap from the same file
System.Drawing.Bitmap image = new System.Drawing.Bitmap("FILE_PATH");
// This is an implicit conversion from System.Drawing.Bitmap to IronSoftware.Drawing.AnyBitmap
// This step is necessary if you are working with System.Drawing.Bitmap and need to convert to IronSoftware.Drawing.AnyBitmap for processing
IronSoftware.Drawing.AnyBitmap anyBitmap = AnyBitmap.FromBitmap(image);
// Save the resulting AnyBitmap from casting as a PNG file
anyBitmap.SaveAs("result-from-casting.png");
ImportsIronSoftware.DrawingImportsSystem.IOImportsSystem.Drawing' Create a new AnyBitmap object from a file' Replace "FILE_PATH" with the actual path of the image you want to processPrivate bitmap = AnyBitmap.FromFile("FILE_PATH")' Save the AnyBitmap object as a JPEG filebitmap.SaveAs("result.jpg")' Export the AnyBitmap as a byte array' This can be useful if you want to send the image data over a network or save it in a databaseDim bytes = bitmap.ExportBytes()' Create a memory stream to export the AnyBitmap as a JPEG stream with 100% qualityUsing resultExport = New MemoryStream() ' This exports the image to the stream with the specified format and quality bitmap.ExportStream(resultExport, AnyBitmap.ImageFormat.Jpeg, 100) ' Be sure to use 'using' or manually close the stream to release resourcesEndUsing' Casting between System.Drawing.Bitmap and IronSoftware.Drawing.AnyBitmap' Load a System.Drawing.Bitmap from the same fileDim image As New System.Drawing.Bitmap("FILE_PATH")' This is an implicit conversion from System.Drawing.Bitmap to IronSoftware.Drawing.AnyBitmap' This step is necessary if you are working with System.Drawing.Bitmap and need to convert to IronSoftware.Drawing.AnyBitmap for processingDim anyBitmap AsIronSoftware.Drawing.AnyBitmap = AnyBitmap.FromBitmap(image)' Save the resulting AnyBitmap from casting as a PNG fileanyBitmap.SaveAs("result-from-casting.png")
Imports IronSoftware.Drawing
Imports System.IO
Imports System.Drawing
' Create a new AnyBitmap object from a file
' Replace "FILE_PATH" with the actual path of the image you want to process
Private bitmap = AnyBitmap.FromFile("FILE_PATH")
' Save the AnyBitmap object as a JPEG file
bitmap.SaveAs("result.jpg")
' Export the AnyBitmap as a byte array
' This can be useful if you want to send the image data over a network or save it in a database
Dim bytes = bitmap.ExportBytes()
' Create a memory stream to export the AnyBitmap as a JPEG stream with 100% quality
Using resultExport = New MemoryStream()
' This exports the image to the stream with the specified format and quality
bitmap.ExportStream(resultExport, AnyBitmap.ImageFormat.Jpeg, 100)
' Be sure to use 'using' or manually close the stream to release resources
End Using
' Casting between System.Drawing.Bitmap and IronSoftware.Drawing.AnyBitmap
' Load a System.Drawing.Bitmap from the same file
Dim image As New System.Drawing.Bitmap("FILE_PATH")
' This is an implicit conversion from System.Drawing.Bitmap to IronSoftware.Drawing.AnyBitmap
' This step is necessary if you are working with System.Drawing.Bitmap and need to convert to IronSoftware.Drawing.AnyBitmap for processing
Dim anyBitmap As IronSoftware.Drawing.AnyBitmap = AnyBitmap.FromBitmap(image)
' Save the resulting AnyBitmap from casting as a PNG file
anyBitmap.SaveAs("result-from-casting.png")
Exemplo de cor
using IronSoftware.Drawing;using System;// The IronSoftware.Drawing library provides enhanced color manipulation features.// This example demonstrates creating color objects and converting between// System.Drawing.Color and IronSoftware.Drawing.Color.// Create a new Color object from a hex string.Color fromHex = Color.FromHex("#191919");// Create a new Color object from RGB values.Color fromRgb = Color.FromRgb(255, 255, 0);// Create a new Color object using an enumeration.Color fromEnum = Color.Crimson;// Casting between System.Drawing.Color and IronSoftware.Drawing.Color.System.Drawing.Color drawingColor = System.Drawing.Color.Red;// Convert System.Drawing.Color to IronSoftware.Drawing.Color.IronSoftware.Drawing.Color ironColor = Color.FromSystemColor(drawingColor);// Access the alpha, red, green, and blue components of the IronSoftware.Drawing.Color.byte alpha = ironColor.A;byte red = ironColor.R;byte green = ironColor.G;byte blue = ironColor.B;// Calculate the luminance of the color.// Luminance is a value from 0 (black) to 100 (white) where 50 is the perceptual "middle grey".double luminance = ironColor.GetLuminance();// Log the calculated attributes to the console.Console.WriteLine($"Color Details - ARGB: ({alpha}, {red}, {green}, {blue}), Luminance: {luminance}");
using IronSoftware.Drawing;
using System;
// The IronSoftware.Drawing library provides enhanced color manipulation features.
// This example demonstrates creating color objects and converting between
// System.Drawing.Color and IronSoftware.Drawing.Color.
// Create a new Color object from a hex string.
Color fromHex = Color.FromHex("#191919");
// Create a new Color object from RGB values.
Color fromRgb = Color.FromRgb(255, 255, 0);
// Create a new Color object using an enumeration.
Color fromEnum = Color.Crimson;
// Casting between System.Drawing.Color and IronSoftware.Drawing.Color.
System.Drawing.Color drawingColor = System.Drawing.Color.Red;
// Convert System.Drawing.Color to IronSoftware.Drawing.Color.
IronSoftware.Drawing.Color ironColor = Color.FromSystemColor(drawingColor);
// Access the alpha, red, green, and blue components of the IronSoftware.Drawing.Color.
byte alpha = ironColor.A;
byte red = ironColor.R;
byte green = ironColor.G;
byte blue = ironColor.B;
// Calculate the luminance of the color.
// Luminance is a value from 0 (black) to 100 (white) where 50 is the perceptual "middle grey".
double luminance = ironColor.GetLuminance();
// Log the calculated attributes to the console.
Console.WriteLine($"Color Details - ARGB: ({alpha}, {red}, {green}, {blue}), Luminance: {luminance}");
ImportsIronSoftware.DrawingImportsSystem' The IronSoftware.Drawing library provides enhanced color manipulation features.' This example demonstrates creating color objects and converting between' System.Drawing.Color and IronSoftware.Drawing.Color.' Create a new Color object from a hex string.Private fromHex AsColor = Color.FromHex("#191919")' Create a new Color object from RGB values.Private fromRgb AsColor = Color.FromRgb(255, 255, 0)' Create a new Color object using an enumeration.Private fromEnum AsColor = Color.Crimson' Casting between System.Drawing.Color and IronSoftware.Drawing.Color.Private drawingColor AsSystem.Drawing.Color = System.Drawing.Color.Red' Convert System.Drawing.Color to IronSoftware.Drawing.Color.Private ironColor AsIronSoftware.Drawing.Color = Color.FromSystemColor(drawingColor)' Access the alpha, red, green, and blue components of the IronSoftware.Drawing.Color.Private alpha AsByte = ironColor.APrivate red AsByte = ironColor.RPrivate green AsByte = ironColor.GPrivate blue AsByte = ironColor.B' Calculate the luminance of the color.' Luminance is a value from 0 (black) to 100 (white) where 50 is the perceptual "middle grey".Private luminance AsDouble = ironColor.GetLuminance()' Log the calculated attributes to the console.Console.WriteLine($"Color Details - ARGB: ({alpha}, {red}, {green}, {blue}), Luminance: {luminance}")
Imports IronSoftware.Drawing
Imports System
' The IronSoftware.Drawing library provides enhanced color manipulation features.
' This example demonstrates creating color objects and converting between
' System.Drawing.Color and IronSoftware.Drawing.Color.
' Create a new Color object from a hex string.
Private fromHex As Color = Color.FromHex("#191919")
' Create a new Color object from RGB values.
Private fromRgb As Color = Color.FromRgb(255, 255, 0)
' Create a new Color object using an enumeration.
Private fromEnum As Color = Color.Crimson
' Casting between System.Drawing.Color and IronSoftware.Drawing.Color.
Private drawingColor As System.Drawing.Color = System.Drawing.Color.Red
' Convert System.Drawing.Color to IronSoftware.Drawing.Color.
Private ironColor As IronSoftware.Drawing.Color = Color.FromSystemColor(drawingColor)
' Access the alpha, red, green, and blue components of the IronSoftware.Drawing.Color.
Private alpha As Byte = ironColor.A
Private red As Byte = ironColor.R
Private green As Byte = ironColor.G
Private blue As Byte = ironColor.B
' Calculate the luminance of the color.
' Luminance is a value from 0 (black) to 100 (white) where 50 is the perceptual "middle grey".
Private luminance As Double = ironColor.GetLuminance()
' Log the calculated attributes to the console.
Console.WriteLine($"Color Details - ARGB: ({alpha}, {red}, {green}, {blue}), Luminance: {luminance}")
Exemplo de retângulo
using IronSoftware.Drawing;using System.Drawing;// Declare an IronSoftware.Drawing.Rectangle objectIronSoftware.Drawing.Rectangle ironRectangle = new IronSoftware.Drawing.Rectangle(5, 5, 50, 50);// Declare a System.Drawing.Rectangle objectSystem.Drawing.Rectangle systemRectangle = new System.Drawing.Rectangle(10, 10, 150, 150);// Implicitly convert System.Drawing.Rectangle to IronSoftware.Drawing.Rectangle// Note: Uncomment and use appropriate conversion methods if available in the IronSoftware.Drawing library// ironRectangle = (IronSoftware.Drawing.Rectangle)systemRectangle;// Output the properties of IronSoftware.Drawing.Rectangle if conversion is successful// These Console.WriteLine statements assume this code runs in a console environmentConsole.WriteLine(ironRectangle.X);Console.WriteLine(ironRectangle.Y);Console.WriteLine(ironRectangle.Width);Console.WriteLine(ironRectangle.Height);
using IronSoftware.Drawing;
using System.Drawing;
// Declare an IronSoftware.Drawing.Rectangle object
IronSoftware.Drawing.Rectangle ironRectangle = new IronSoftware.Drawing.Rectangle(5, 5, 50, 50);
// Declare a System.Drawing.Rectangle object
System.Drawing.Rectangle systemRectangle = new System.Drawing.Rectangle(10, 10, 150, 150);
// Implicitly convert System.Drawing.Rectangle to IronSoftware.Drawing.Rectangle
// Note: Uncomment and use appropriate conversion methods if available in the IronSoftware.Drawing library
// ironRectangle = (IronSoftware.Drawing.Rectangle)systemRectangle;
// Output the properties of IronSoftware.Drawing.Rectangle if conversion is successful
// These Console.WriteLine statements assume this code runs in a console environment
Console.WriteLine(ironRectangle.X);
Console.WriteLine(ironRectangle.Y);
Console.WriteLine(ironRectangle.Width);
Console.WriteLine(ironRectangle.Height);
ImportsIronSoftware.DrawingImportsSystem.Drawing' Declare an IronSoftware.Drawing.Rectangle objectPrivate ironRectangle As New IronSoftware.Drawing.Rectangle(5, 5, 50, 50)' Declare a System.Drawing.Rectangle objectPrivate systemRectangle As New System.Drawing.Rectangle(10, 10, 150, 150)' Implicitly convert System.Drawing.Rectangle to IronSoftware.Drawing.Rectangle' Note: Uncomment and use appropriate conversion methods if available in the IronSoftware.Drawing library' ironRectangle = (IronSoftware.Drawing.Rectangle)systemRectangle;' Output the properties of IronSoftware.Drawing.Rectangle if conversion is successful' These Console.WriteLine statements assume this code runs in a console environmentConsole.WriteLine(ironRectangle.X)Console.WriteLine(ironRectangle.Y)Console.WriteLine(ironRectangle.Width)Console.WriteLine(ironRectangle.Height)
Imports IronSoftware.Drawing
Imports System.Drawing
' Declare an IronSoftware.Drawing.Rectangle object
Private ironRectangle As New IronSoftware.Drawing.Rectangle(5, 5, 50, 50)
' Declare a System.Drawing.Rectangle object
Private systemRectangle As New System.Drawing.Rectangle(10, 10, 150, 150)
' Implicitly convert System.Drawing.Rectangle to IronSoftware.Drawing.Rectangle
' Note: Uncomment and use appropriate conversion methods if available in the IronSoftware.Drawing library
' ironRectangle = (IronSoftware.Drawing.Rectangle)systemRectangle;
' Output the properties of IronSoftware.Drawing.Rectangle if conversion is successful
' These Console.WriteLine statements assume this code runs in a console environment
Console.WriteLine(ironRectangle.X)
Console.WriteLine(ironRectangle.Y)
Console.WriteLine(ironRectangle.Width)
Console.WriteLine(ironRectangle.Height)
Exemplo de fonte
using System;using System.Drawing;using IronSoftware.Drawing;// Create a new Font object with a specified font family, style, and sizeIronSoftware.Drawing.Font font = new IronSoftware.Drawing.Font("Times New Roman", FontStyle.Italic | FontStyle.Bold, 30);// Create a new instance of System.Drawing.FontSystem.Drawing.Font drawingFont = new System.Drawing.Font("Courier New", 30);try{ // Attempt to cast System.Drawing.Font to IronSoftware.Drawing.Font // Note: This cast may not be directly possible if the libraries do not support each other; // additional conversion logic might be required. IronSoftware.Drawing.Font ironFont = new IronSoftware.Drawing.Font(drawingFont.FontFamily.Name, drawingFont.Style, drawingFont.Size); // Accessing properties of the IronSoftware.Drawing.Font object string familyName = ironFont.FamilyName; // Get the font family name FontStyle style = ironFont.Style; // Get the combined font style (italic, bold, etc.) float size = ironFont.Size; // Get the font size bool isItalic = ironFont.Italic; // Determine if the font style includes Italic bool isBold = ironFont.Bold; // Determine if the font style includes Bold // Output the font properties to verify correctnessConsole.WriteLine($"Family: {familyName}, Style: {style}, Size: {size}, Italic: {isItalic}, Bold: {isBold}");}catch (InvalidCastException){Console.WriteLine("The conversion between System.Drawing.Font and IronSoftware.Drawing.Font is not directly supported.");}catch (Exception ex){Console.WriteLine($"An error occurred: {ex.Message}");}
using System;
using System.Drawing;
using IronSoftware.Drawing;
// Create a new Font object with a specified font family, style, and size
IronSoftware.Drawing.Font font = new IronSoftware.Drawing.Font("Times New Roman", FontStyle.Italic | FontStyle.Bold, 30);
// Create a new instance of System.Drawing.Font
System.Drawing.Font drawingFont = new System.Drawing.Font("Courier New", 30);
try
{
// Attempt to cast System.Drawing.Font to IronSoftware.Drawing.Font
// Note: This cast may not be directly possible if the libraries do not support each other;
// additional conversion logic might be required.
IronSoftware.Drawing.Font ironFont = new IronSoftware.Drawing.Font(drawingFont.FontFamily.Name, drawingFont.Style, drawingFont.Size);
// Accessing properties of the IronSoftware.Drawing.Font object
string familyName = ironFont.FamilyName; // Get the font family name
FontStyle style = ironFont.Style; // Get the combined font style (italic, bold, etc.)
float size = ironFont.Size; // Get the font size
bool isItalic = ironFont.Italic; // Determine if the font style includes Italic
bool isBold = ironFont.Bold; // Determine if the font style includes Bold
// Output the font properties to verify correctness
Console.WriteLine($"Family: {familyName}, Style: {style}, Size: {size}, Italic: {isItalic}, Bold: {isBold}");
}
catch (InvalidCastException)
{
Console.WriteLine("The conversion between System.Drawing.Font and IronSoftware.Drawing.Font is not directly supported.");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
ImportsSystemImportsSystem.DrawingImportsIronSoftware.Drawing' Create a new Font object with a specified font family, style, and sizePrivate font As New IronSoftware.Drawing.Font("Times New Roman", FontStyle.ItalicOrFontStyle.Bold, 30)' Create a new instance of System.Drawing.FontPrivate drawingFont As New System.Drawing.Font("Courier New", 30)Try ' Attempt to cast System.Drawing.Font to IronSoftware.Drawing.Font ' Note: This cast may not be directly possible if the libraries do not support each other; ' additional conversion logic might be required. Dim ironFont As New IronSoftware.Drawing.Font(drawingFont.FontFamily.Name, drawingFont.Style, drawingFont.Size) ' Accessing properties of the IronSoftware.Drawing.Font object Dim familyName AsString = ironFont.FamilyName' Get the font family name Dim style AsFontStyle = ironFont.Style' Get the combined font style (italic, bold, etc.) Dim size AsSingle = ironFont.Size' Get the font size Dim isItalic AsBoolean = ironFont.Italic' Determine if the font style includes Italic Dim isBold AsBoolean = ironFont.Bold' Determine if the font style includes Bold ' Output the font properties to verify correctnessConsole.WriteLine($"Family: {familyName}, Style: {style}, Size: {size}, Italic: {isItalic}, Bold: {isBold}")Catch e1 AsInvalidCastExceptionConsole.WriteLine("The conversion between System.Drawing.Font and IronSoftware.Drawing.Font is not directly supported.")Catch ex AsExceptionConsole.WriteLine($"An error occurred: {ex.Message}")EndTry
Imports System
Imports System.Drawing
Imports IronSoftware.Drawing
' Create a new Font object with a specified font family, style, and size
Private font As New IronSoftware.Drawing.Font("Times New Roman", FontStyle.Italic Or FontStyle.Bold, 30)
' Create a new instance of System.Drawing.Font
Private drawingFont As New System.Drawing.Font("Courier New", 30)
Try
' Attempt to cast System.Drawing.Font to IronSoftware.Drawing.Font
' Note: This cast may not be directly possible if the libraries do not support each other;
' additional conversion logic might be required.
Dim ironFont As New IronSoftware.Drawing.Font(drawingFont.FontFamily.Name, drawingFont.Style, drawingFont.Size)
' Accessing properties of the IronSoftware.Drawing.Font object
Dim familyName As String = ironFont.FamilyName ' Get the font family name
Dim style As FontStyle = ironFont.Style ' Get the combined font style (italic, bold, etc.)
Dim size As Single = ironFont.Size ' Get the font size
Dim isItalic As Boolean = ironFont.Italic ' Determine if the font style includes Italic
Dim isBold As Boolean = ironFont.Bold ' Determine if the font style includes Bold
' Output the font properties to verify correctness
Console.WriteLine($"Family: {familyName}, Style: {style}, Size: {size}, Italic: {isItalic}, Bold: {isBold}")
Catch e1 As InvalidCastException
Console.WriteLine("The conversion between System.Drawing.Font and IronSoftware.Drawing.Font is not directly supported.")
Catch ex As Exception
Console.WriteLine($"An error occurred: {ex.Message}")
End Try
Suporte disponível
Licença
As informações sobre a licença podem ser encontradas aqui: LICENSE.txt
Contribuir
Se você deseja contribuir para o projeto de código aberto IronDrawing, leia a licença antes de enviar uma solicitação de pull request para o repositório no GitHub .
Curtis Chau é bacharel em Ciência da Computação (Universidade Carleton) e se especializa em desenvolvimento front-end, com experiência em Node.js, TypeScript, JavaScript e React. Apaixonado por criar interfaces de usuário intuitivas e esteticamente agradáveis, Curtis gosta de trabalhar com frameworks modernos e criar manuais bem estruturados e visualmente atraentes.