Я пытаюсь установить прозрачность круга на растровое изображение в C# .NET Winforms. Я попытался сделать это с помощью Graphics.DrawEllipse так:Установить прозрачность круга на растровое изображение
private void setCircleAlpha(int alpha, ref Bitmap b, ColumnVector2 pos, int diameter)
{
Graphics g = Graphics.FromImage(b);
SolidBrush sb = new SolidBrush(Color.FromArgb(0, 0, 0, 0));
g.FillEllipse(sb, pos.X, pos.Y, diameter, diameter);
}
, но это не то, что я хочу, как это рисует прозрачный круг над изображением вместо того, чтобы прозрачность этого круга.
я прибег к использованию этого чрезвычайно медленный кода:
private void setCircleAlpha(int alpha, ref Bitmap b, ColumnVector2 pos, int diameter)
{
//Calculate the square root of the radius
float radius = diameter/2;
float sqRadius = radius * radius;
//Calculate the centre of the circle
ColumnVector2 centre = pos + new ColumnVector2(radius, radius);
for (int x = (int)pos.X; x < pos.X + diameter; x++)
{
for (int y = (int)pos.Y; y < pos.Y + diameter; y++)
{
//Calculate the distance between the centre of the circle and the point being tested
ColumnVector2 vec = new ColumnVector2(x, y) - centre;
//If the distance between a point and the centre of a circle is less than the radius of that circle then that point is in the circle.
//Calculate distance using pythagoras (a^2 + b^2 = c^2)
//Square both the distance and radius to eliminate need for square root
float sqDist = (vec.X * vec.X) + (vec.Y * vec.Y);
if (sqDist < sqRadius)
{
b.SetPixel(x, y, Color.FromArgb(alpha, b.GetPixel(x, y)));
}
}
}
}
Мой вопрос: Есть ли лучше/быстрее способ сделать это?
Обратите внимание, что я не требую более быстрых алгоритмов генерации окружения, вместо этого я задаю альтернативные варианты графики.
Используйте 1-й фрагмент кода. Вы ищете свойство Graphics.CompositingMode, установите его в SourceCopy –