縦書きのテキストを表示するマルチブラウザページがあります。
すべてのブラウザでテキストを垂直方向にレンダリングするための醜いハックとして、テキストが垂直方向に描画された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を返すので、適切なアルファ透明度をサポートできます。
.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 );
}
}
これでアルファは機能しているように見えますが、テキストはブロック状に見えます。まるでジャギーエッジが残っているかのように見えますが、背景は黒です。
これは.Net/GDI +のバグですか?gifのインデックスの透明度でも失敗することはすでにわかっているので、あまり自信がありません。
この画像は、これがうまくいかない2つの方法を示しています。
上の画像は、白い背景やMakeTransparent
呼び出しなしでそれを示しています。2つ目は、背景が白で塗りつぶされMakeTransparent
、インデックスの透明度を追加するために呼び出されます。
これらはどちらも正しくありません。2番目の画像には、私が望まない白いエイリアシングジャギーがあり、最初の画像は黒に対してしっかりとエイリアシングされているように見えます。