110,539
社区成员
发帖
与我相关
我的任务
分享
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing.Imaging;
public class Form1
{
/// <summary>
/// 获取遮罩层的相对反相
/// </summary>
/// <param name="MaskImage">遮罩层</param>
/// <param name="BackGroundImage">背景层</param>
/// <remarks></remarks>
private void GetInvtImg(ref Bitmap MaskImage, Bitmap BackGroundImage)
{
try {
BitmapData bmpDATA1 = new BitmapData();
BitmapData bmpDATA2 = new BitmapData();
bmpDATA1 = BackGroundImage.LockBits(new Rectangle(0, 0, BackGroundImage.Width, BackGroundImage.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
bmpDATA2 = MaskImage.LockBits(new Rectangle(0, 0, MaskImage.Width, MaskImage.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
byte[] BTS1 = new byte[bmpDATA1.Stride * bmpDATA1.Height + 1];
byte[] BTS2 = new byte[bmpDATA2.Stride * bmpDATA2.Height + 1];
System.Runtime.InteropServices.Marshal.Copy(bmpDATA1.Scan0, BTS1, 0, BTS1.Length - 1);
System.Runtime.InteropServices.Marshal.Copy(bmpDATA2.Scan0, BTS2, 0, BTS2.Length - 1);
if (BTS1.Length != BTS2.Length) {
throw new Exception("请确保遮罩层与背景层大小一致");
return;
}
for (int I = 0; I <= BTS2.Length - 4; I += 4) {
if (BTS2[I + 3] != 0) {
BTS2[I] = 255 - BTS1[I];
BTS2[I + 1] = 255 - BTS1[I + 1];
BTS2[I + 2] = 255 - BTS1[I + 2];
}
}
System.Runtime.InteropServices.Marshal.Copy(BTS2, 0, bmpDATA2.Scan0, BTS2.Length - 1);
BackGroundImage.UnlockBits(bmpDATA1);
MaskImage.UnlockBits(bmpDATA2);
} catch (Exception ex) {
throw new Exception(ex.Message);
}
}
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//定义一个空图层,大小为背景大小
using (Bitmap B = new Bitmap(this.BackgroundImage.Width, this.BackgroundImage.Height)) {
using (Graphics G = Graphics.FromImage(B)) {
//在该图层上绘制需要的形状,颜色不限
G.DrawEllipse(new Pen(Brushes.Red, 30), new Rectangle(40, 40, 200, 180));
}
//将该图层处理为背景反相
GetInvtImg(ref B, this.BackgroundImage);
using (Graphics G = Graphics.FromImage(this.BackgroundImage)) {
G.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias;
//将处理后的反相图绘制到背景
G.DrawImage(B, new Rectangle(0, 0, B.Width, B.Height), new Rectangle(0, 0, B.Width, B.Height), GraphicsUnit.Pixel);
}
}
this.Refresh();
}
}