방법: 컨트롤의 배경에 텍스트 그리기
텍스트 문자열을 FormattedText 개체로 변환한 다음, 개체를 컨트롤의 DrawingContext에 그려서 컨트롤의 배경에 직접 텍스트를 그릴 수 있습니다. 이 기술을 사용하여 Panel에서 파생된 개체의 배경을 그릴 수도 있습니다(예: Canvas 및 StackPanel).
사용자 지정 텍스트 배경이 있는 컨트롤의 예
예제
컨트롤의 배경을 그리려면 새 DrawingBrush 개체를 만들고 개체의 DrawingContext에 대한 변환된 텍스트를 그립니다. 그런 다음, 새 DrawingBrush를 컨트롤의 배경 속성에 할당합니다.
다음 코드 예제에서는 FormattedText 개체를 만들고 Label 및 Button 개체의 배경에 그리는 방법을 보여 줍니다.
// Handle the WindowLoaded event for the window.
private void WindowLoaded(object sender, EventArgs e)
{
// Update the background property of the label and button.
myLabel.Background = new DrawingBrush(DrawMyText("My Custom Label"));
myButton.Background = new DrawingBrush(DrawMyText("Display Text"));
}
// Convert the text string to a geometry and draw it to the control's DrawingContext.
private Drawing DrawMyText(string textString)
{
// Create a new DrawingGroup of the control.
DrawingGroup drawingGroup = new DrawingGroup();
// Open the DrawingGroup in order to access the DrawingContext.
using (DrawingContext drawingContext = drawingGroup.Open())
{
// Create the formatted text based on the properties set.
FormattedText formattedText = new FormattedText(
textString,
CultureInfo.GetCultureInfo("en-us"),
FlowDirection.LeftToRight,
new Typeface("Comic Sans MS Bold"),
48,
System.Windows.Media.Brushes.Black // This brush does not matter since we use the geometry of the text.
);
// Build the geometry object that represents the text.
Geometry textGeometry = formattedText.BuildGeometry(new System.Windows.Point(20, 0));
// Draw a rounded rectangle under the text that is slightly larger than the text.
drawingContext.DrawRoundedRectangle(System.Windows.Media.Brushes.PapayaWhip, null, new Rect(new System.Windows.Size(formattedText.Width + 50, formattedText.Height + 5)), 5.0, 5.0);
// Draw the outline based on the properties that are set.
drawingContext.DrawGeometry(System.Windows.Media.Brushes.Gold, new System.Windows.Media.Pen(System.Windows.Media.Brushes.Maroon, 1.5), textGeometry);
// Return the updated DrawingGroup content to be used by the control.
return drawingGroup;
}
}
참고 항목
GitHub에서 Microsoft와 공동 작업
이 콘텐츠의 원본은 GitHub에서 찾을 수 있으며, 여기서 문제와 끌어오기 요청을 만들고 검토할 수도 있습니다. 자세한 내용은 참여자 가이드를 참조하세요.
.NET Desktop feedback
피드백
https://aka.ms/ContentUserFeedback
출시 예정: 2024년 내내 콘텐츠에 대한 피드백 메커니즘으로 GitHub 문제를 단계적으로 폐지하고 이를 새로운 피드백 시스템으로 바꿀 예정입니다. 자세한 내용은 다음을 참조하세요.다음에 대한 사용자 의견 제출 및 보기