■ Bitmap 클래스를 사용해 이미지 나선 효과를 만드는 방법을 보여준다.
▶ MainForm.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 |
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Windows.Forms; namespace TestProject { /// <summary> /// 메인 폼 /// </summary> public partial class MainForm : Form { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 색상 배열 /// </summary> private Color[] colorArray = { Color.Red, Color.OrangeRed, Color.Yellow, Color.Green, Color.Blue, Color.Indigo, Color.Fuchsia, }; /// <summary> /// 소스 비트맵 /// </summary> private Bitmap sourceBitmap = null; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainForm() /// <summary> /// 생성자 /// </summary> public MainForm() { InitializeComponent(); this.openMenuItem.Click += openMenuItem_Click; this.saveAsMenuItem.Click += saveAsMenuItem_Click; this.thicknessTextBox.TextChanged += parameterTextBox_TextChanged; this.colorScaleTextBox.TextChanged += parameterTextBox_TextChanged; this.opacityTextBox.TextChanged += parameterTextBox_TextChanged; this.drawOutlineCheckBox.CheckedChanged += parameterCheckBox_CheckedChanged; this.applyEllipticalMaskCheckBox.CheckedChanged += parameterCheckBox_CheckedChanged; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #region 열기 메뉴 항목 클릭시 처리하기 - openMenuItem_Click(sender, e) /// <summary> /// 열기 메뉴 항목 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void openMenuItem_Click(object sender, EventArgs e) { if(this.openFileDialog.ShowDialog() == DialogResult.OK) { this.sourceBitmap = LoadBitmapUnlocked(this.openFileDialog.FileName); DrawImage(); } } #endregion #region 다른 이름으로 저장 메뉴 항목 클릭시 처리하기 - saveAsMenuItem_Click(sender, e) /// <summary> /// 다른 이름으로 저장 메뉴 항목 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void saveAsMenuItem_Click(object sender, EventArgs e) { if(this.saveFileDialog.ShowDialog() == DialogResult.OK) { SaveImage(this.pictureBox.Image, this.saveFileDialog.FileName); } } #endregion #region 매개 변수 텍스트 박스 텍스트 변경시 처리하기 - parameterTextBox_TextChanged(sender, e) /// <summary> /// 매개 변수 텍스트 박스 텍스트 변경시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void parameterTextBox_TextChanged(object sender, EventArgs e) { DrawImage(); } #endregion #region 매개 변수 체크 박스 체크 변경시 처리하기 - parameterCheckBox_CheckedChanged(sender, e) /// <summary> /// 매개 변수 체크 박스 체크 변경시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void parameterCheckBox_CheckedChanged(object sender, EventArgs e) { DrawImage(); } #endregion //////////////////////////////////////////////////////////////////////////////// Function #region 잠금 없이 비트맵 로드하기 - LoadBitmapUnlocked(filePath) /// <summary> /// 잠금 없이 비트맵 로드하기 /// </summary> /// <param name="filePath">파일 경로</param> /// <returns>비트맵</returns> private Bitmap LoadBitmapUnlocked(string filePath) { using(Bitmap bitmap = new Bitmap(filePath)) { return new Bitmap(bitmap); } } #endregion #region 이미지 저장하기 - SaveImage(image, filePath) /// <summary> /// 이미지 저장하기 /// </summary> /// <param name="image">이미지</param> /// <param name="filePath">파일 경로</param> private void SaveImage(Image image, string filePath) { string fileExtension = Path.GetExtension(filePath); switch(fileExtension.ToLower()) { case ".bmp" : image.Save(filePath, ImageFormat.Bmp ); break; case ".exif" : image.Save(filePath, ImageFormat.Exif); break; case ".gif" : image.Save(filePath, ImageFormat.Gif ); break; case ".jpg" : case ".jpeg" : image.Save(filePath, ImageFormat.Jpeg); break; case ".png" : image.Save(filePath, ImageFormat.Png ); break; case ".tif" : case ".tiff" : image.Save(filePath, ImageFormat.Tiff); break; default : throw new NotSupportedException($"알 수 없는 파일 확장자 : {fileExtension}"); } } #endregion #region 거리 구하기 - GetDistance(point1, point2) /// <summary> /// 거리 구하기 /// </summary> /// <param name="point1">포인트 1</param> /// <param name="point2">포인트 2</param> /// <returns>거리</returns> private float GetDistance(PointF point1, PointF point2) { float deltaX = point1.X - point2.X; float deltaY = point1.Y - point2.Y; return (float)Math.Sqrt(deltaX * deltaX + deltaY * deltaY); } #endregion #region 거리 구하기 - GetDistance(point, rectangle) /// <summary> /// 거리 구하기 /// </summary> /// <param name="point">포인트</param> /// <param name="rectangle">사각형</param> /// <returns>거리</returns> private float GetDistance(PointF point, Rectangle rectangle) { float maximumDistance = GetDistance(point, new PointF(rectangle.Left, rectangle.Top)); float testDistance = GetDistance(point, new PointF(rectangle.Left, rectangle.Bottom)); if(maximumDistance < testDistance) { maximumDistance = testDistance; } testDistance = GetDistance(point, new PointF(rectangle.Right, rectangle.Top)); if(maximumDistance < testDistance) { maximumDistance = testDistance; } testDistance = GetDistance(point, new PointF(rectangle.Right, rectangle.Bottom)); if(maximumDistance < testDistance) { maximumDistance = testDistance; } return maximumDistance; } #endregion #region 극 좌표 → 직교 좌표 변환하기 - ConvertPolarToCartesian(radius, theta, x, y) /// <summary> /// 극 좌표 → 직교 좌표 변환하기 /// </summary> /// <param name="radius">반경</param> /// <param name="theta">세타</param> /// <param name="x">X</param> /// <param name="y">Y</param> private void ConvertPolarToCartesian(float radius, float theta, out float x, out float y) { x = (float)(radius * Math.Cos(theta)); y = (float)(radius * Math.Sin(theta)); } #endregion #region 나선 포인트 리스트 구하기 - GetSpiralPointList(centerPoint, thickness, angleOffset, maximumTheta) /// <summary> /// 나선 포인트 리스트 구하기 /// </summary> /// <param name="centerPoint">중심 포인트</param> /// <param name="thickness">두께</param> /// <param name="angleOffset">각도 오프셋</param> /// <param name="maximumTheta">최대 세타</param> /// <returns>나선 포인트 리스트</returns> private List<PointF> GetSpiralPointList(PointF centerPoint, float thickness, float angleOffset, float maximumTheta) { List<PointF> pointList = new List<PointF>(); const float deltaTheta = (float)(5 * Math.PI / 180); for(float theta = 0; ; theta += deltaTheta) { float radius = thickness * theta; float x; float y; ConvertPolarToCartesian(radius, theta + angleOffset, out x, out y); x += centerPoint.X; y += centerPoint.Y; pointList.Add(new PointF((float)x, (float)y)); if(theta + angleOffset > maximumTheta) { break; } } return pointList; } #endregion #region 색상화 비트맵 구하기 - GetColorizeBitmap(sourceBitmap, color, colorScale) /// <summary> /// 색상화 비트맵 구하기 /// </summary> /// <param name="sourceBitmap">소스 비트맵</param> /// <param name="color">색상</param> /// <param name="colorScale">색상 스케일</param> /// <returns>색상화 비트맵</returns> private Bitmap GetColorizeBitmap(Bitmap sourceBitmap, Color color, float colorScale) { ColorMatrix colorMatrix = new ColorMatrix ( new float[][] { new float[] { color.R / 255f * colorScale, 0 , 0 , 0, 0}, new float[] { 0 , color.G / 255f * colorScale, 0 , 0, 0}, new float[] { 0 , 0 , color.B / 255f * colorScale, 0, 0}, new float[] { 0 , 0 , 0 , 1, 0}, new float[] { 0 , 0 , 0 , 0, 1} } ); int width = sourceBitmap.Width; int height = sourceBitmap.Height; Bitmap targetBitmap = new Bitmap(width, height); using(ImageAttributes imageAttributes = new ImageAttributes()) { imageAttributes.SetColorMatrix(colorMatrix); using(Graphics graphics = Graphics.FromImage(targetBitmap)) { Point[] targetPointArray = { new Point(0 , 0 ), new Point(width, 0 ), new Point(0 , height) }; Rectangle sourceRectangle = new Rectangle(0, 0, width, height); graphics.DrawImage ( sourceBitmap, targetPointArray, sourceRectangle, GraphicsUnit.Pixel, imageAttributes ); } } return targetBitmap; } #endregion #region 타원형 비트맵 구하기 - GetEllipticalBitmap(sourceBitmap) /// <summary> /// 타원형 비트맵 구하기 /// </summary> /// <param name="sourceBitmap">소스 비트맵</param> /// <returns>타원형 비트맵</returns> private Bitmap GetEllipticalBitmap(Bitmap sourceBitmap) { Bitmap targetBitmap = (Bitmap)sourceBitmap.Clone(); using(Graphics graphics = Graphics.FromImage(targetBitmap)) { graphics.Clear(Color.Transparent); using(TextureBrush brush = new TextureBrush(sourceBitmap)) { Rectangle rectangle = new Rectangle(0, 0, sourceBitmap.Width, sourceBitmap.Height); graphics.FillEllipse(brush, rectangle); } } return targetBitmap; } #endregion #region 나선 비트맵 구하기 - SpiralizeBitmap(sourceBitmap, colorArray, thickness, colorScale, opacity, drawOutline, applyEllipticalMask) /// <summary> /// 나선 비트맵 구하기 /// </summary> /// <param name="sourceBitmap">소스 비트맵</param> /// <param name="colorArray">색상 배열</param> /// <param name="thickness">두께</param> /// <param name="colorScale">색상 스케일</param> /// <param name="opacity">불투명도</param> /// <param name="drawOutline">윤곽선 그리기 여부</param> /// <param name="applyEllipticalMask">타원 마스크 적용 여부</param> /// <returns>나선 비트맵</returns> private Bitmap SpiralizeBitmap ( Bitmap sourceBitmap, Color[] colorArray, float thickness, float colorScale, float opacity, bool drawOutline, bool applyEllipticalMask ) { int width = sourceBitmap.Width; int height = sourceBitmap.Height; Bitmap spiralBitmap = new Bitmap(width, height); using(Graphics graphics = Graphics.FromImage(spiralBitmap)) { graphics.Clear(this.pictureBox.BackColor); graphics.SmoothingMode = SmoothingMode.AntiAlias; int spiralCount = colorArray.Length; float angularSpacing = (float)(2 * Math.PI / spiralCount); float startAngle = 0; PointF centerPoint = new PointF(width / 2, height / 2); Rectangle rectangle = new Rectangle(0, 0, width, height); float maximumDistance = GetDistance(centerPoint, rectangle); float maximumTheta = maximumDistance / thickness + 2 * (float)Math.PI; List<List<PointF>> spiralPointList = new List<List<PointF>>(); for(int i = 0; i <= spiralCount; i++) { spiralPointList.Add ( GetSpiralPointList ( centerPoint, thickness, startAngle, maximumTheta ) ); startAngle += angularSpacing; } for(int i = 0; i < spiralCount; i++) { List<PointF> pointList1 = new List<PointF>(spiralPointList[i ]); List<PointF> pointList2 = new List<PointF>(spiralPointList[i + 1]); pointList2.Reverse(); pointList1.AddRange(pointList2); using(Bitmap colorizedBitmap = GetColorizeBitmap(this.sourceBitmap, this.colorArray[i], colorScale)) { using(TextureBrush brush = new TextureBrush(colorizedBitmap)) { graphics.FillPolygon(brush, pointList1.ToArray()); } } if(drawOutline) { graphics.DrawLines(Pens.Black, pointList1.ToArray()); } } } Bitmap targetBitmap = (Bitmap)sourceBitmap.Clone(); using(Graphics graphics = Graphics.FromImage(targetBitmap)) { ColorMatrix colorMatrix = new ColorMatrix(); colorMatrix.Matrix33 = opacity; ImageAttributes imageAttributes = new ImageAttributes(); imageAttributes.SetColorMatrix ( colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap ); Rectangle rectangle = new Rectangle(0, 0, targetBitmap.Width, targetBitmap.Height); graphics.DrawImage ( spiralBitmap, rectangle, 0, 0, targetBitmap.Width, targetBitmap.Height, GraphicsUnit.Pixel, imageAttributes ); } if(applyEllipticalMask) { targetBitmap = GetEllipticalBitmap(targetBitmap); } return targetBitmap; } #endregion #region 이미지 그리기 - DrawImage() /// <summary> /// 이미지 그리기 /// </summary> private void DrawImage() { if(this.sourceBitmap == null) { return; } float thickness; float colorScale; float opacity; if(!float.TryParse(this.thicknessTextBox.Text, out thickness)) { return; } if(!float.TryParse(this.colorScaleTextBox.Text, out colorScale)) { return; } if(!float.TryParse(this.opacityTextBox.Text, out opacity)) { return; } this.pictureBox.Image = SpiralizeBitmap ( this.sourceBitmap, this.colorArray, thickness, colorScale, opacity, this.drawOutlineCheckBox.Checked, this.applyEllipticalMaskCheckBox.Checked ); } #endregion } } |