前言
接着上週寫的截圖控件繼續更新添加 文字。
1.WPF實現截屏「仿微信」
2.WPF 實現截屏控件之移動(二)「仿微信」
3.WPF 截圖控件之伸縮(三) 「仿微信」
4.WPF 截圖控件之繪製方框與橢圓(四) 「仿微信」
5.WPF 截圖控件之繪製箭頭(五)「仿微信」
6.WPF 截圖控件之繪製箭頭禁止越界(六)「仿微信」
正文
一、接着ScreenCut繼續發電。
1)添加文字操作只允許在可編輯區域內
- 在添加文字、使用
Border
嵌套TextBox
Border需注意:
1)當控件的高存放不下內容的時候需要將控件的SetTop
設置向上移動,最大不能超過Rect
的Top
需要監聽寬高發生變化SizeChanged
TextBox需注意:
1)需要監聽失去光標焦點LostKeyboardFocus後找TextBox
的父控件設置邊框爲零。
👇
void DrawText()
{
if (pointStart.Value.X < rect.Right
&&
pointStart.Value.X > rect.Left
&&
pointStart.Value.Y > rect.Top
&&
pointStart.Value.Y < rect.Bottom)
{
var currentWAndX = pointStart.Value.X + 40;
if (textBorder == null)
{
textBorder = new Border
{
BorderBrush = _currentBrush == null ? Brushes.Red : _currentBrush,
BorderThickness = new Thickness(1),
Tag = _tag
};
var textBox = new TextBox();
textBox.Style = null;
textBox.Background = null;
textBox.BorderThickness = new Thickness(0);
textBox.Foreground = textBorder.BorderBrush;
textBox.FontFamily = DrawingContextHelper.FontFamily;
textBox.FontSize = 16;
textBox.TextWrapping = TextWrapping.Wrap;
textBox.FontWeight = FontWeights.Bold;
textBox.MinWidth = _width;
textBox.MaxWidth = rect.Right - pointStart.Value.X;
textBox.MaxHeight = rect.Height;
textBox.Cursor = Cursors.Hand;
textBox.Padding = new Thickness(4);
textBox.LostKeyboardFocus += (s, e1) =>
{
var tb = s as TextBox;
var parent = VisualTreeHelper.GetParent(tb);
if (parent != null && parent is Border border)
{
border.BorderThickness = new Thickness(0);
if (string.IsNullOrWhiteSpace(tb.Text))
_canvas.Children.Remove(border);
}
};
textBorder.SizeChanged += (s, e1) =>
{
var tb = s as Border;
var y = y1;
if (y + tb.ActualHeight > rect.Bottom)
{
var v = Math.Abs(rect.Bottom - (y + tb.ActualHeight));
y1 = y - v;
Canvas.SetTop(tb, y1);
}
};
textBorder.PreviewMouseLeftButtonDown += (s, e) =>
{
SelectElement();
var border = s as Border;
border.BorderThickness = new Thickness(1);
frameworkElement = border;
frameworkElement.Opacity = .7;
};
textBorder.Child = textBox;
_canvas.Children.Add(textBorder);
textBox.Focus();
var x = pointStart.Value.X;
if (currentWAndX > rect.Right)
x = x - (currentWAndX - rect.Right);
Canvas.SetLeft(textBorder, x);
Canvas.SetTop(textBorder, pointStart.Value.Y);
}
}
}
2)移除焦點 。
Keyboard.ClearFocus();