我正在使用這個函式來生成一個簡單的漸變位圖LinearGradientBrush,最后我將其保存為檔案以用作墻紙。但問題是結果看起來并不“平滑”,它看起來相當“不穩定”,因為你可以看到顏色的線條。
我使用螢屏的邊界作為位圖的尺寸,增加尺寸并不能提高質量(我嘗試了 2 倍甚至 4 倍)。
我嘗試設定InterpolationModeandSmoothingMode但似乎都沒有對最終結果產生影響。
有沒有辦法解決這個問題?
public static Bitmap GenerateGradient(Color color1, Color color2, int width, int height, LinearGradientMode mode)
{
Bitmap bitmap = new(width, height);
using (Graphics graphics = Graphics.FromImage(bitmap))
using (LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, width, height), color1, color2, mode))
{
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.FillRectangle(brush, new Rectangle(0, 0, width, height));
}
return bitmap;
}
編輯:這是我呼叫函式并保存位圖的方式,在重新檢查代碼后,我認為問題主要在于我如何生成顏色陰影。使用命名顏色代替生成陰影后,結果更加平滑。
//Generates a random shade of the specified color
//by randomly adjusting the alpha value.
public static Color RandomShade(Color color)
{
var random = new Random(DateTime.Now.Millisecond);
int alpha = random.Next(0, 255);
return Color.FromArgb(alpha, color);
}
private void buttonGenerate_Click(object sender, EventArgs e)
{
int width = Screen.PrimaryScreen.Bounds.Width;
int height = Screen.PrimaryScreen.Bounds.Height;
Color color1 = RandomShade(Color.AliceBlue);
Color color2 = RandomShade(Color.Navy);
var bitmap = GenerateGradient(color1, color2, width, height, LinearGradientMode.ForwardDiagonal);
bitmap.Save("wallpaper.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
}
使用生成的陰影

使用命名顏色

uj5u.com熱心網友回復:
問題在于RandomShade()方法。通過使用 Alpha 通道生成陰影,漸變也會插入此通道。
我認為可以產生更好結果的方法是使用其他三個(顏色)通道隨機變暗或變亮顏色,并保持 alpha 不變。換句話說,只改變顏色的亮度。
例如:
public static Color RandomShadeV2(Color color)
{
const int Range = 1000;
const int Variance = 700;
var random = new Random(DateTime.Now.Millisecond);
int factor = random.Next(Range - Variance, Range Variance 1);
int r = color.R * factor / Range;
int g = color.G * factor / Range;
int b = color.B * factor / Range;
return Color.FromArgb(255, Math.Min(r, 255), Math.Min(g, 255), Math.Min(b, 255));
}
這將生成亮度因子在原始顏色的 0.3 到 1.7 之間的陰影。
沒有特別的理由為亮度乘數選擇這些值。這些是我正在測驗的。例如,如果您選擇 0.0 到 2.0,您可能會經常得到非常暗或非常亮的陰影。和常數是我用來推導亮度因子的:范圍始終是整體(如 100%)Range;Variance和方差是我允許它從那一點開始變化的,在這種情況下,700 代表 70%,所以最終因素將在 100% - 70% = 30% = 0.3 和 100% 70% = 170% = 1.7 之間.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/411199.html
標籤:
