C# -- comboBox 이미지 item 그리기
C# -- comboBox 이미지 item 그리기
참고: http://csharphelper.com/blog/2016/03/make-a-combobox-display-colors-or-images-in-c/
https://stackoverflow.com/questions/10891214/c-sharp-combobox-with-lines
** 사용자가 직접 그려서 comboBox 만들때
0. ComboBoxStyle 은 반드시 DropDownList 로 지정해야함.
1. comboBox 의 DrawMode 를, OwnerDrawVariable 로 설정한다.
this.ComboBox1.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
-- comboBox 크기가 변하지 않는 다면, OwnerDrawFixed 로 설정한다.
2. comboBox 각 item의 height, width 변경할려면, MeasureItem event 를 처리하면 됨.
-- 그냥 쉽게 가상함수OnMeasureItem( ) 메소드를 재정의하여 사용해도 됨.
3. item 내용을 직접그릴때는 DrawItem event 에서 처리하면됨.
-- MeasureItem event 이후에 DrawItem event 호출됨.
-- 그냥 쉽게 가상함수 OnDrawItem( ) 메소드를 재정의하여 사용해도 됨.
< 실행결과 >
--> 계속 combobox 선택시 내용 안보여서, 내용보여주기위해 기능없는 button1 만듦.
< 소스코드 >
--
using System; | |
using System.Drawing; | |
using System.Windows.Forms; | |
namespace combobox_image_test | |
{ | |
public partial class Form1 : Form | |
{ | |
private int[] _lineWidth = { 1, 3, 5, 7 }; // 선 두께 수치. | |
public Form1() | |
{ | |
InitializeComponent(); | |
} | |
private void Form1_Load(object sender, EventArgs e) | |
{ | |
this.comboBox1.DropDownStyle = ComboBoxStyle.DropDownList; // 필수!!!! | |
this.comboBox1.DrawMode = DrawMode.OwnerDrawVariable; | |
//this.comboBox1.DrawMode = DrawMode.OwnerDrawFixed; | |
//this.comboBox1.Items.Clear(); | |
foreach (int lineWidth in _lineWidth) | |
{ | |
this.comboBox1.Items.Add(lineWidth); | |
} | |
//this.comboBox1.TabIndex = 0; | |
this.comboBox1.SelectedIndex = 0; | |
} | |
private void comboBox1_MeasureItem(object sender, MeasureItemEventArgs e) | |
{ | |
Console.WriteLine("mesureitem event..."); | |
} | |
private void comboBox1_DrawItem(object sender, DrawItemEventArgs e) | |
{ | |
Console.WriteLine("drawitem event..."); | |
Console.WriteLine($"e.Bounds.Left={e.Bounds.Left}, e.Bounds.Right={e.Bounds.Right}"); | |
Console.WriteLine($"e.Bounds.X={e.Bounds.X}, e.Bounds.Y={e.Bounds.Y}"); | |
Console.WriteLine($"e.Bounds.Width={e.Bounds.Width}, e.Bounds.Height={e.Bounds.Height}"); | |
if (e.Index < 0) | |
{ | |
//Console.WriteLine(" .... e.Index < 0...."); | |
return; | |
} | |
e.DrawBackground(); | |
Point startPt = new Point(e.Bounds.Left + 50, e.Bounds.Y + 5); // 선 시작점 | |
Point endPt = new Point(e.Bounds.Right - 5, e.Bounds.Y + 5); // 선 끝점. | |
// 해당 크기의 선 그리기 | |
using (Pen pen = new Pen(e.ForeColor, (int)this.comboBox1.Items[e.Index])) | |
{ | |
e.Graphics.DrawLine(pen, startPt, endPt); | |
} | |
// 선 크기도 combobox 에 출력한다 | |
using(Font fnt = new Font(this.comboBox1.Font.FontFamily, 10)) | |
{ | |
e.Graphics.DrawString(this.comboBox1.Items[e.Index].ToString(), fnt, Brushes.Red, e.Bounds.X + 10, e.Bounds.Y); | |
} | |
e.DrawFocusRectangle(); | |
} | |
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) | |
{ | |
// combobox에서 선택한 선크기 출력하기. | |
this.label1.Text = $"selected line width = {this.comboBox1.Items[this.comboBox1.SelectedIndex].ToString()}"; | |
} | |
} | |
} |