Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharp_Graphics.doc
Скачиваний:
20
Добавлен:
16.11.2019
Размер:
3.1 Mб
Скачать

Компиляция кода

Предыдущий пример предназначен для работы с Windows Forms, для него необходим объект PaintEventArgs e, передаваемый в качестве параметра обработчику события PaintEventHandler.

How to: Use a Color Matrix to Set Alpha Values in Images

The Bitmap class (which inherits from the Image class) and the ImageAttributes class provide functionality for getting and setting pixel values. You can use the ImageAttributes class to modify the alpha values for an entire image, or you can call the SetPixel method of the Bitmap class to modify individual pixel values.

Example

The ImageAttributes class has many properties that you can use to modify images during rendering. In the following example, an ImageAttributes object is used to set all the alpha values to 80 percent of what they were. This is done by initializing a color matrix and setting the alpha scaling value in the matrix to 0.8. The address of the color matrix is passed to the SetColorMatrix method of the ImageAttributes object, and the ImageAttributes object is passed to the DrawString method of the Graphics object.

During rendering, the alpha values in the bitmap are converted to 80 percent of what they were. This results in an image that is blended with the background. As the following illustration shows, the bitmap image looks transparent; you can see the solid black line through it.

Where the image is over the white portion of the background, the image has been blended with the color white. Where the image crosses the black line, the image is blended with the color black.

Использование матрицы цветов для задания значений прозрачности в изображениях

Классы Bitmap (наследующий у класса Image) и ImageAttributes предоставляют функции для чтения и записи значений точек. Для изменения альфа-компонентов во всем изображении можно использовать класс ImageAttributes, либо можно вызывать метод SetPixel класса Bitmap для изменения значений отдельных точек.

Пример

Класс ImageAttributes содержит множество свойств, которые можно использовать для модификаций изображений при их визуализации. В следующем примере объект ImageAttributes используется для установки значений всех альфа-компонентов равными 80 процентам от их первоначальных значений. Для этого выполняется инициализация матрицы цветов и установка в этой матрице масштабирующего коэффициента для альфа-компонента равным 0,8. Адрес матрицы цветов передается методу SetColorMatrix объекта ImageAttributes, а объект ImageAttributes передается методу DrawString объекта Graphics.

В процессе визуализации значения альфа-компонентов растрового изображения преобразуются и становятся равными 80% от их первоначальных значений. Это приводит к смешиванию изображения и фона. Как показано на следующем рисунке, растровое изображение выглядит прозрачным, и сквозь него можно видеть сплошную черную линию.

В местах, где изображение покрывает белые участки фона, оно смешивается с белым цветом. Там, где изображение пересекает черную линию, оно смешивается с черным цветом.

// Create the Bitmap object and load it with the texture image.

Bitmap bitmap = new Bitmap("Texture.jpg");

// Initialize the color matrix.

// Note the value 0.8 in row 4, column 4.

float[][] matrixItems ={

new float[] {1, 0, 0, 0, 0},

new float[] {0, 1, 0, 0, 0},

new float[] {0, 0, 1, 0, 0},

new float[] {0, 0, 0, 0.8f, 0},

new float[] {0, 0, 0, 0, 1}};

ColorMatrix colorMatrix = new ColorMatrix(matrixItems);

// Create an ImageAttributes object and set its color matrix.

ImageAttributes imageAtt = new ImageAttributes();

imageAtt.SetColorMatrix(

colorMatrix,

ColorMatrixFlag.Default,

ColorAdjustType.Bitmap);

// First draw a wide black line.

e.Graphics.DrawLine(

new Pen(Color.Black, 25),

new Point(10, 35),

new Point(200, 35));

// Now draw the semitransparent bitmap image.

int iWidth = bitmap.Width;

int iHeight = bitmap.Height;

e.Graphics.DrawImage(

bitmap,

new Rectangle(30, 0, iWidth, iHeight), // destination rectangle

0.0f, // source rectangle x

0.0f, // source rectangle y

iWidth, // source rectangle width

iHeight, // source rectangle height

GraphicsUnit.Pixel,

imageAtt);

Compiling the Code

The preceding example is designed for use with Windows Forms, and it requires PaintEventArgse, which is a parameter of PaintEventHandler.

-------------