RoundCLip.vb
'' 
'' このコードは、DioDocs for Imaging のサンプルの一部として提供されています。
'' © MESCIUS inc. All rights reserved.
'' 
Imports System.IO
Imports System.Drawing
Imports System.Collections.Generic
Imports System.Linq
Imports System.Numerics
Imports GrapeCity.Documents.Drawing
Imports GrapeCity.Documents.Text
Imports GrapeCity.Documents.Imaging

'' このサンプルは、画像の一部を円形にクリッピングし、
'' GcBitmap に描画する方法を示します。
Public Class RoundCLip
    Function GenerateImage(
        ByVal pixelSize As Size,
        ByVal dpi As Single,
        ByVal opaque As Boolean,
        Optional ByVal sampleParams As String() = Nothing) As GcBitmap

        '' 注意:単色の背景の代わりに Color.Transparent を使用することもできますが、
        '' これが期待通りに動作するためには、結果の画像フォーマットが
        '' 透明度をサポートしている必要があります。
        Dim backColor = Color.FromArgb(&HFF0066CC)
        Dim foreColor = Color.FromArgb(&HFFFFCC00)
        Const bottom = 144, pad = 36
        Dim minSize = Math.Min(pixelSize.Width, pixelSize.Height) / 6, maxSize = (Math.Min(pixelSize.Width, pixelSize.Height) / 1.5)

        '' サンプルのいくつかのパラメータをランダム化します。
        Dim rnd = Util.NewRandom()

        '' 不要になったビットマップは破棄(Dispose)するのが良いため、
        '' 返却されるもの以外のすべてのビットマップに 'Using' を使用しています。
        Using bmpSrc = New GcBitmap(Path.Combine("Resources", "Stock", "woman-brick-wall.jpg"))
            '' 元の画像とターゲットの不透明度が一致することを確認します。
            bmpSrc.Opaque = opaque

            '' 元の画像におけるクリッピングの座標とサイズです。
            Const x = 143, y = 0, w = 655, h = 655

            '' 指定された円の外側をすべて除外するクリッピング領域を作成します。
            Dim rgn = New GrapeCity.Documents.Imaging.Region(New RectangularFigure(0, 0, bmpSrc.PixelWidth, bmpSrc.PixelHeight))
            Dim ellipse = New EllipticFigure(x, y, w, h)
            rgn.CombineWithRegion(New GrapeCity.Documents.Imaging.Region(ellipse), RegionCombineMode.Exclude, False)

            '' リージョンを使用してクリップするには、BitmapRenderer を使用する必要があります。
            '' 注意(v2sp2の新機能):レンダラーはデフォルトでは作成されないため、
            '' 使用する前に EnsureRendererCreated() を呼び出す必要があります。
            bmpSrc.EnsureRendererCreated()
            Dim renderer = bmpSrc.Renderer
            renderer.ClipRegion = rgn
            renderer.Clear(Color.Transparent)
            Dim size = rnd.Next(minSize, maxSize)
            Using bmpRound = bmpSrc.Clip(New Rectangle(x, y, w, h))
                Using bmpSmall = bmpRound.Resize(size, size)
                    Dim bmp = New GcBitmap(pixelSize.Width, pixelSize.Height, opaque, dpi, dpi)
                    bmp.Clear(Color.Transparent)
                    bmp.BitBlt(bmpSmall,
                        rnd.Next(pad, pixelSize.Width - pad - bmpSmall.PixelWidth),
                        rnd.Next(pad, pixelSize.Height - pad - bottom - bmpSmall.PixelHeight))
                    Return bmp
                End Using
            End Using
        End Using
    End Function
End Class