2016-05-28 33 views
1

我正在玩微软视觉API和学习C#,因为我走了,Vision对象的属性之一是图像的“重点颜色”。C#LinearGradientBrush垂直重复的位图

从一系列分析图像中,我想要显示以线性渐变排序的那些颜色 - 因为那样可以向用户显示大多数图片都是(例如)蓝色,因为蓝色占用了一半梯度等

我有这个工作,因为我订购颜色由色相,并能够产生一个线性渐变我填充到位图。

,但默认情况下,梯度是水平的,我需要垂直 - 所以我用LinearGradientBrush.RotateTransform(90)其旋转,实际的梯度很好,但似乎并没有填满整个矩形,它重复。这是我得到的结果:

enter image description here

如何创建一个垂直的LinearGradient,填补了矩形对象的整个高度为我的位图?

这里是我的代码:

private Bitmap CreateColorGradient(System.Drawing.Rectangle rect, System.Drawing.Color[] colors) 
    { 
     Bitmap gradient = new Bitmap(rect.Width, rect.Height); 

     LinearGradientBrush br = new LinearGradientBrush(rect, System.Drawing.Color.White, System.Drawing.Color.White, 0, false); 
     ColorBlend cb = new ColorBlend(); 

     // Positions 
     List<float> positions = new List<float>(); 
     for (int i = 0; i < colors.Length; i++) positions.Add((float)i/(colors.Length - 1)); 
     cb.Positions = positions.ToArray(); 

     cb.Colors = colors; 
     br.InterpolationColors = cb; 
     br.RotateTransform(90); 

     using (Graphics g = Graphics.FromImage(gradient)) 
      g.FillRectangle(br, rect); 

     return gradient; 
    } 

感谢您的阅读和任何帮助 - 如果你还看到在我的代码的东西,可以做的更好,请指出来,这样有助于我学习:)

回答

3

您忽略constructor中的angle参数。而当你在Grahics对象上进行旋转时,你的画笔矩形不再适合目标位图,而且渐变无法填充它;所以它重复。

要纠正

  • 简单的角度设置为90
  • 删除br.RotateTransform(90);电话。

这里这改变了结果从左边到中间版本:

enter image description hereenter image description hereenter image description here

虽然我们看着它,不要采取LinearGradientBrushWrapMode财产的音符。您在第一张图片中看到的是默认的WrapMode.Clamp。通常情况下,转换到翻转模式有助于......所以让我们看看它在正确位置上的第一个版本的影响。

它看起来像WrapMode.TileFlipY但因为我已经带回旋转实际发生值WrapMode.TileFlipXWrapMode.TileFlipXYbr.WrapMode = WrapMode.TileFlipX;

+0

辉煌,这看起来惊人谢谢! –

+0

没问题。看看关于WrapMode的最后评论,这经常会很方便。 – TaW