2015-01-12 69 views
7

Si consideri il seguente codice da uno standard System.Windows.Forms.FormLinearGradientBrush non rende correttamente

protected override void OnPaint(PaintEventArgs e) 
{ 
    base.OnPaint(e); 
    Rectangle test = new Rectangle(50, 50, 100, 100); 
    using (LinearGradientBrush brush = new LinearGradientBrush(test, Color.Red, Color.Blue, 0f)) 
    { 
     e.Graphics.DrawRectangle(new Pen(brush, 8), test); 
    } 
} 

Produce questo risultato:

enter image description here

Perché sono le linee rosse e blu che mostra nell'ordine errato e come può essere risolto?

risposta

2

L'origine del rendering è il problema. Stai chiedendo un Pen largo 8 px e che 8px sia definito come 4px esterno in entrambe le direzioni rispetto alla linea definita dal tuo rettangolo. Ciò è dovuto al valore predefinito di Alignment=Center. Se si imposta per utilizzare Alignment=Inset, si otterranno risultati migliori.

Si può vedere questa linea con la semplice aggiunta di questo al vostro codice originale:

e.Graphics.DrawRectangle(Pens.White, test); 

cambiare il metodo di essere tale, e funzionerà:

Rectangle test = new Rectangle(50, 50, 100, 100); 
using (LinearGradientBrush brush = new LinearGradientBrush(test, Color.Red, Color.Blue, 0f)) 
{ 
    using (var pen = new Pen(brush, 8f)) 
    { 
     pen.Alignment = PenAlignment.Inset; 
     e.Graphics.DrawRectangle(pen, test); 
    } 
} 
Problemi correlati