我有一个显示垂直文本的多浏览器页面。
作为让文本在所有浏览器中垂直呈现的丑陋技巧,我创建了一个自定义页面处理程序,它返回一个带有垂直绘制文本的 PNG。
这是我的基本代码(C#3,但对任何其他版本进行了小改动,直到 1):
Font f = GetSystemConfiguredFont();
//this sets the text to be rotated 90deg clockwise (i.e. down)
StringFormat stringFormat = new StringFormat { FormatFlags = StringFormatFlags.DirectionVertical };
SizeF size;
// creates 1Kx1K image buffer and uses it to find out how bit the image needs to be to fit the text
using ( Image imageg = (Image) new Bitmap( 1000, 1000 ) )
size = Graphics.FromImage( imageg ).
MeasureString( text, f, 25, stringFormat );
using ( Bitmap image = new Bitmap( (int) size.Width, (int) size.Height ) )
{
Graphics g = Graphics.FromImage( (Image) image );
g.FillRectangle( Brushes.White, 0f, 0f, image.Width, image.Height );
g.TranslateTransform( image.Width, image.Height );
g.RotateTransform( 180.0F ); //note that we need the rotation as the default is down
// draw text
g.DrawString( text, f, Brushes.Black, 0f, 0f, stringFormat );
//make be background transparent - this will be an index (rather than an alpha) transparency
image.MakeTransparent( Color.White );
//note that this image has to be a PNG, as GDI+'s gif handling renders any transparency as black.
context.Response.AddHeader( "ContentType", "image/png" );
using ( MemoryStream memStream = new MemoryStream() )
{
image.Save( memStream, ImageFormat.Png );
memStream.WriteTo( context.Response.OutputStream );
}
}
这会创建一个看起来像我想要的图像,除了透明度是基于索引的。当我返回 PNG 时,它可以支持适当的 alpha 透明度。
有没有办法在.net中做到这一点?
感谢 Vlix(见评论)我做了一些改变,虽然它仍然不正确:
using ( Bitmap image = new Bitmap( (int) size.Width, (int) size.Height, PixelFormat.Format32bppArgb ) )
{
Graphics g = Graphics.FromImage( (Image) image );
g.TranslateTransform( image.Width, image.Height );
g.RotateTransform( 180.0F ); //note that we need the rotation as the default is down
// draw text
g.DrawString( text, f, Brushes.Black, 0f, 0f, stringFormat );
//note that this image has to be a PNG, as GDI+'s gif handling renders any transparency as black.
context.Response.AddHeader( "ContentType", "image/png" );
using ( MemoryStream memStream = new MemoryStream() )
{
//note that context.Response.OutputStream doesn't support the Save, but does support WriteTo
image.Save( memStream, ImageFormat.Png );
memStream.WriteTo( context.Response.OutputStream );
}
}
现在 alpha 似乎可以工作了,但文本看起来是块状的 - 好像它仍然有锯齿状的边缘,但在黑色背景下。
这是 .Net/GDI+ 的一些错误吗?我已经发现它甚至无法用于 gif 的索引透明胶片,所以我对它没有多大信心。
此图像显示了出错的两种方式:
顶部图像显示它没有白色背景或MakeTransparent
呼叫。第二个用背景填充白色然后MakeTransparent
调用添加索引透明度。
这些都不正确 - 第二个图像有我不想要的白色锯齿锯齿,第一个图像似乎与黑色完全混叠。