如何在PowerShell中使用LinearGradientBrush填充矩形?

时间:2016-03-08 16:00:05

标签: powershell system.drawing lineargradientbrush

我有一些可爱的PowerShell代码,来自另一个答案,但我希望能够在块中添加渐变填充结束:

Add-Type -AssemblyName System.Drawing
$bmp = new-object System.Drawing.Bitmap 208,61
$brushBg = [System.Drawing.Brushes]::Blue

# replace this line...
$brushGr = [System.Drawing.Brushes]::Yellow

$graphics = [System.Drawing.Graphics]::FromImage($bmp)
$graphics.FillRectangle($brushBg,0,0,$bmp.Width,$bmp.Height)
$graphics.FillRectangle($brushGr ,$bmp.Width-50,0,50,$bmp.Height)
$graphics.Dispose()
$bmp.Save($filename)
到目前为止Google还不是我的朋友,因为我不明白如何将C#和VB的MSDN文档与PowerShell相提并论。我对替换线的猜测是这样的:

# ... with these lines
$col1 = new-object System.Drawing.Color.FromRgb( 209, 227, 250)
$col2 = new-object System.Drawing.Color.FromRgb(170, 199, 238)
$pt1  = new-object System.Drawing.Point(0.5, 0)
$pt2  = new-object System.Drawing.Point(0.5, 1)
$brushGr  = new-object System.Drawing.LinearGradientBrush( $col1 , $col2, $pt1, $pt2)

非常感谢任何帮助。

感谢下面Dharmatech的精彩回答,如果它对任何人有用,这里是我最终用于绘制标记栏的工作代码(保存在MYFILENAME.ps1中,并使用{{1}运行它}})

powershell -ExecutionPolicy Bypass -file MYFILENAME.ps1

1 个答案:

答案 0 :(得分:2)

这是一个似乎有用的例子:

Add-Type -AssemblyName System.Drawing

$bitmap = New-Object System.Drawing.Bitmap 100, 100

$p0 = New-Object System.Drawing.Point(0, 0)
$p1 = New-Object System.Drawing.Point(100, 100)

$c0 = [System.Drawing.Color]::FromArgb(255, 255, 0, 0)
$c1 = [System.Drawing.Color]::FromArgb(255, 0, 0, 255)

$brush = New-Object System.Drawing.Drawing2D.LinearGradientBrush($p0, $p1, $c0, $c1)

$graphics = [System.Drawing.Graphics]::FromImage($bitmap)

$graphics.FillRectangle($brush, 0, 0, $bitmap.Width, $bitmap.Height)

$bitmap.Save('c:\temp\test.bmp')

结果图片:

enter image description here

这是使用内联表达式的变体:

Add-Type -AssemblyName System.Drawing

$bitmap = New-Object System.Drawing.Bitmap 100, 100

[System.Drawing.Graphics]::FromImage($bitmap).FillRectangle(
    (New-Object System.Drawing.Drawing2D.LinearGradientBrush(
        (New-Object System.Drawing.Point(0, 0)), 
        (New-Object System.Drawing.Point(100, 100)),
        [System.Drawing.Color]::FromArgb(255, 255, 0, 0),
        [System.Drawing.Color]::FromArgb(255, 0, 0, 255))),
    0, 0, $bitmap.Width, $bitmap.Height)

$bitmap.Save('c:\temp\test-d.bmp')