如何在LockBits数组中使用DrawEllipse(如何生成一组形成椭圆的像素)

时间:2015-07-20 16:53:26

标签: arrays vb.net bitmap ellipse lockbits

我使用此类根据LockBits函数填充位图的像素:

Imports System.Drawing.Imaging
Imports System.Runtime.InteropServices.Marshal

Public Class Fill

    Public Shared Function Process(ByVal b As Bitmap) As Bitmap

    Dim bmd As BitmapData = _
    b.LockBits(New Rectangle(0, 0, b.Width, b.Height), _
    System.Drawing.Imaging.ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb)

    Dim scan0 As IntPtr = bmd.Scan0
    Dim stride As Integer = bmd.Stride

    ' Here's the speedier method.
    ' define an array to store each pixels color as an int32 
    Dim pixels(b.Width * b.Height - 1) As Integer

    ' this is system.runtime.interopservices.marshall.copy
    Copy(scan0, pixels, 0, pixels.Length)

    ' loop through all pixels and fill

    For i As Integer = 0 To pixels.Length - 1
        pixels(i) = Color.Red.ToArgb
    Next

    ' Copy the data back from the array to the locked memory
    Copy(pixels, 0, scan0, pixels.Length)

    ' finally we unlock the bits. 
    b.UnlockBits(bmd)
    Return b
    End Function
End Class

现在,我不需要填充所有像素,而是需要填充一个椭圆(实际上它将是许多省略号,这就是我使用LockBits的原因),所以我用Google搜索了一种方法来绘制使用某种公式逐像素的椭圆,但我没有找到太多的帮助,我对这个数学的东西也不好。 所以,我的问题是:如何创建一个形成填充椭圆的像素数组?谢谢

补充(随意忽略):

我将准确解释我尝试做什么,这样可以帮助您了解我的情况。 实际上,我正在开发一个函数,它应该生成具有随机宽度和宽度的填充椭圆。位图特定区域的高度(在特定范围内),而填充像素必须占该区域中像素总数的百分比,这就是为什么我需要逐像素地绘制椭圆(或使用一个像素数组),以跟踪填充像素的数量。

1 个答案:

答案 0 :(得分:2)

椭圆内所有点的公式为:

x,y are the coordinates of any point on the ellipse

其中
a, b are the radius on the x and y axes respectively
h,k the coordinates of the center
Dim h, k, a, b, x, y As Integer Dim res As Double 'arbitrary values of ellipse h = 200 k = 200 a = 80 b = 60 For x = h - a To h + a For y = k - b To k + b res = CDbl((x - h) * (x - h)) / CDbl(a * a) + CDbl((y - k) * (y - k)) / CDbl(b * b) If res <= 1.0 Then 'the point (x, y) is inside End If Next Next

所以代码:

{{1}}