Как задать цвет в c
Перейти к содержимому

Как задать цвет в c

  • автор:

Как задать цвет в c

За установку цвета фона и текста элементов отвечают свойства BackgroundColor и TextColor соответственно. В качестве значение они принимают объект класса Microsoft.Maui.Graphics.Color :

В данном случае для определения цвета применялись встроенные готовые цвета из статического класса Colors.

Установка цвета в .NET MAUI и C#

Кроме встроенных готовых цветов типа Colors.DarkBlue (так называемых именнованных цветов) также для установки цвета мы можем указать и другие значения, можно использовать один из конструкторов класса Color. Некоторые из них:

new Color(float grayShade) : устанавливает тон серого цвета

new Color(float r, float g, float b) : устанавливает компоненты красного, зеленого и синего. Каждая компонента должна иметь значения в диапазоне от 0.0 до 1.0

new Color(byte r, byte g, byte b) : устанавливает компоненты красного, зеленого и синего. Каждая компонента должна иметь значения в диапазоне от 0 до 255

new Color(float r, float g, float b, float a) : добавляет еще один параметр — a , который передает прозрачность и имеет значение от 0.0 (полностью прозрачный) до 1.0 (не прозрачный)

new Color(byte r, byte g, byte b, byte a) : устанавливает компоненты красного, зеленого, синего и прозрачности

BackgtoundColor и TextColor в .NET MAUI и C#

Также для установки цвета мы можем использовать ряд статических методов:

Color.FromArgb(string hex) : возвращает объект Color, созданный по переданному в качестве параметра шестнадцатеричному значению. В качестве значения в метод передается строка в формате «#AARRGGBB», «#RRGGBB», «#ARGB» или «RGB», где A — показатель прозрачности, R — значение для красного цвета, G — значение для зеленого компонента и B — представляет синий цвет

Color.FromRgb(double r, double g, double b) : возвращает объект Color, для которого также устанавливаются компоненты красного, зеленого и синего

Color.FromRgb(int r, int g, int b) : аналогичен предыдущей версии метода, только теперь компоненты красного, зеленого и синего имеют целочисленные значения от 0 до 255

Color.FromRgba(double r, double g, double b, double a) : добавляет параметр прозрачности со значением от 0.0 (полностью прозрачный) до 1.0 (не прозрачный)

Color.FromRgba(int r, int g, int b, int a) : добавляет параметр прозрачности со значением от 0 (полностью прозрачный) до 255 (не прозрачный)

Color.FromHsla(double h, double s, double l, double a) : устанавливает последовательно параметры h (hue — тон цвета), s (saturation — насыщенность), l (luminosity — яркость) и прозрачность.

В xaml мы можем задавать цвет с помощью шестнадцатеричных значений также, как в HTML/CSS:

Управление цветом

Стоит отметить, что у класса Color определено ряд дополнительных методов, которые позволяют управлять цветом. В частности, ряд методов позволяются выполнять преобразования

ToHex : возвращает шестнадцатеричное значение текущего цвета в виде строки.

ToArgbHex : возвращает шестнадцатеричное значение текущего цвета в виде строки в формате ARGB

ToRgbaHex : возвращает шестнадцатеричное значение текущего цвета в виде строки в формате RGBA

ToInt : возвращает числовое ARGB-представление текущего цвета в виде значения int

ToUint : возвращает числовое ARGB-представление текущего цвета в виде значения uint

ToRgb : преобразует текущей цвет в отдельные компоненты RGB типа byte

ToRgba : преобразует текущей цвет в отдельные компоненты RGBA типа byte

ToHsl : преобразует текущей цвет в отдельные компоненты HSL типа float

Кроме того, у класса Color есть ряд дополнительных методов для управления отдельными аспектами цвета

AddLuminosity : добавляет цвету яркость

MultiplyAlpha : умножает альфа-компоненту (прозрачность) цвета на переданное значение типа float

Set System.Drawing.Color values

Hi how to set R G B values in System.Drawing.Color.G ?

which is like System.Drawing.Color.G=255; is not allowed because its read only

i just need to create a Color Object by assigning custom R G B values

6 Answers 6

You could create a color using the static FromArgb method:

You can also specify the alpha using the following overload.

The Color structure is immutable (as all structures should really be), meaning that the values of its properties cannot be changed once that particular instance has been created.

Instead, you need to create a new instance of the structure with the property values that you want. Since you want to create a color using its component RGB values, you need to use the FromArgb method:

Как изменить цвет в программе на C

wikiHow работает по принципу вики, а это значит, что многие наши статьи написаны несколькими авторами. При создании этой статьи над ее редактированием и улучшением работали, в том числе анонимно, 13 человек(а).

Количество просмотров этой статьи: 13 521.

Изменение цвета текста или фигур в программе на C позволит выделить их при запуске программы пользователем. Процесс изменения цвета текста и фигур является довольно простым, так как все необходимые функции содержатся в стандартных библиотеках. Вы можете изменить цвет всего, что выводится на экран.

C# Color Examples

Color is a struct. This type provides a standard way to specify and mutate colors in the C# language.

By adding a reference to the System.Drawing assembly, you can access this type and avoid writing your own color routines.

Example. First, let's examine a program that uses a named color property. It then accesses several instance properties on the variable and also calls methods. You can acquire many known colors by using the named properties on the Color type.

Note: For a more complete list, please scroll down and view the names themselves.

Colors can be represented as ARGB values, which store the alpha transparency, as well as the red, green and blue values. These values are stored as bytes which gives them a range of 0 to 255 inclusive.

Won't compile? If you try to execute this program and it won't compile, please try adding the System.Drawing assembly through the interface in Visual Studio. Some project types, such as Windows Forms, include this assembly automatically.

Known colors. Occasionally, you may have a known color and want to acquire a Color struct from it for usage elsewhere. For example, you can query the system for the color of the menu text, using the KnownColor.MenuText enum.

And: Then convert it into a regular color. This lets you examine the components of the color programmatically.

Convert. It is possible to represent colors as an integer that represents the byte values of the ARGB values. Each of those values is one byte. The four bytes together constitute a single 32-bit integer.

You can persist the ARGB integer to text files or databases to save storage space. It also will occupy less memory in your program as it executes. Please notice how the ToArgb() and FromArgb() methods are used to go back and forth.

FromName. In some cases, you may have to convert from a string to a color type. For example, if you accept user input and the user types the word "white", you can convert this into a real color and use it with the Color.FromName method.

Note: This won't work for color names that are not recognized in the list of properties.

Empty colors. The Color type is a struct type, and so cannot be set to null. Instead of using null, please use the Color.Empty value. Then, whenever you want to see if the color is still empty, acquire the IsEmpty instance property on the variable.

Here: This example shows one case where the color is empty, and one case where the color is not empty.

Windows Forms. A common place to use the Color type is in the Windows Forms framework. The WPF framework also uses Color instances. Forms require the Color type for when you want to set their backgrounds and foregrounds.

In this example, we use the Color.FromName method to convert the string value into an actual color. We then set the form's background to that color. This results in a thoroughly green window.

Named colors. There are many different known and named colors in the .NET Framework. These are accessible through static properties on the Color type. Please see the first example to see how to get the color values.

Also: This site shows the visual appearance of these colors in another article.

Summary. By providing a unified interface for acquiring and mutating color values, the Color type fills a useful niche in the .NET Framework. It is found in the System.Drawing namespace and assembly.

So: You can access known colors, convert colors to integers, parse colors, and generally make the world a brighter place with this type.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *