As part of the project I'm working on, I have to keep and restore areas of the magic wand from the image. To retrieve data for storage, I use the GetRegionData method . As stated in the specification, this method:
Returns a RegionData that represents information describing this region.
I store byte[], stored in a property RegionData.Datain a base64 string, so I can get it RegionDatalater through a somewhat unconventional method:
var regionData =
(RegionData)FormatterServices.GetUninitializedObject(typeof(RegionData));
regionData.Data = bytes;
Then I create Regionand pass the above object RegionDatain the constructor and call GetRegionScansto get the rectangle objects that make up the area:
var region = new Region(regionData);
RectangleF[] rectangles = region.GetRegionScans(new Matrix());
, , . WinForms, :
using (var g = Graphics.FromImage(picBox.Image))
{
var p = new Pen(Color.Black, 1f);
var alternatePen = new Pen(Color.BlueViolet, 1f);
var b = new SolidBrush(picBox.BackColor);
var niceBrush = new SolidBrush(Color.Orange);
foreach (var r in rectangles)
{
g.DrawRectangle(p,
new Rectangle(new Point((int)r.Location.X, (int)r.Location.Y),
new Size((int)r.Width, (int)r.Height)));
}
}
, :

- , . , , , . - , .
, , , . :
var pointPair = new[]
{
new Point((int) r.Left, (int) r.Y),
new Point((int) r.Right, (int) r.Y)
};
g.DrawRectangle(p, pointPair[0].X, pointPair[0].Y, 1, 1);
g.DrawRectangle(p, pointPair[1].X, pointPair[1].Y, 1, 1);
:

, .
, . -, , , .
, Left, Right , .
, .
!
Peter Duniho . SafeHandle , , .
, .
private void DrawRegionOutline(Graphics graphics, Color color, Region region)
{
var regionHandle = new SafeRegionHandle(region, region.GetHrgn(graphics));
var deviceContext = new SafeDeviceContextHandle(graphics);
var brushHandle = new SafeBrushHandle(color);
using (regionHandle)
using (deviceContext)
using (brushHandle)
FrameRgn(deviceContext.DangerousGetHandle(), regionHandle.DangerousGetHandle(), brushHandle.DangerousGetHandle(), 1, 1);
}
SafeHandleNative
SafeHandleZeroOrMinusOneIsInvalid, , .
[HostProtection(MayLeakOnAbort = true)]
[SuppressUnmanagedCodeSecurity]
public abstract class SafeNativeHandle : SafeHandleZeroOrMinusOneIsInvalid
{
#region Platform Invoke
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
protected internal static extern bool CloseHandle(IntPtr hObject);
#endregion
protected SafeNativeHandle() : base(true)
{}
protected SafeNativeHandle(IntPtr handle)
: base(true)
{
SetHandle(handle);
}
}
, Region, Brush . SafeNativeHandle, , , , . , Win32 API, .
public class SafeRegionHandle : SafeNativeHandle
{
private readonly Region _region;
public SafeRegionHandle(Region region, IntPtr handle)
{
_region = region;
base.handle = handle;
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
protected override bool ReleaseHandle()
{
try
{
_region.ReleaseHrgn(handle);
}
catch
{
return false;
}
return true;
}
}