using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespace WindowsFormsApplication8
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
public enum States
{
Normal,
Pushed,
Poped
}
public class CustomButton : Button
{
protected override void OnPaint(PaintEventArgs pevent)
{
Graphics g = pevent.Graphics;
int X = this.Width;
int Y = this.Height;
Point[] points = {
new Point(0, 0),
new Point(X, 0),
new Point(X, Y),
new Point(0, Y),
new Point(0, 0)};
GraphicsPath path = new GraphicsPath();
path.AddLines(points);
this.Region = new Region(path);
SolidBrush sBrush = new SolidBrush(SystemColors.Control);
g.FillPath(sBrush, path);
g.DrawLine(new Pen(Color.Black), 0, 0, this.Width-1, 0);
g.DrawLine(new Pen(Color.Black), this.Width-1, 0, this.Width-1, this.Height-1);
g.DrawLine(new Pen(Color.Black), this.Width-1, this.Height-1, 0, this.Height-1);
g.DrawLine(new Pen(Color.Black), 0, this.Height-1, 0, 0);
if (this.Text != "")
{
StringFormat stringFormat = new StringFormat();
switch (this.TextAlign)
{
case ContentAlignment.MiddleCenter:
stringFormat.LineAlignment = StringAlignment.Center;
stringFormat.Alignment = StringAlignment.Center;
break;
case ContentAlignment.MiddleRight:
stringFormat.LineAlignment = StringAlignment.Far;
stringFormat.Alignment = StringAlignment.Center;
break;
default: break;
}
SolidBrush drawBrush = new SolidBrush(Color.Black);
Size s = TextRenderer.MeasureText(this.Text, this.Font);
RectangleF rectf = new Rectangle(Point.Empty, s);
g.DrawString(this.Text, this.Font, drawBrush, rectf, stringFormat);
}
}
}
}
为什么Button的Text文字,设置TextAlign = MiddleRight 一点作用都没呢,StringFormat 为什么没起作用
------解决思路----------------------
// 可以去掉以下两行。你计算出一个紧贴的外框,如何有空间让内容在外框内上下左右对齐?
// Size s = TextRenderer.MeasureText(this.Text, this.Font);
// RectangleF rectf = new Rectangle(Point.Empty, s);
g.DrawString(this.Text, this.Font, drawBrush, this.ClientRectangle, stringFormat);
------解决思路----------------------
你上下两个分支都是
stringFormat.Alignment = StringAlignment.Center;
当然都一样。