Компактный каркас: заполнить прямоугольник проблемой с кистью - PullRequest
2 голосов
/ 11 января 2010

В моем мобильном проекте я хочу заполнить прямоугольник полупрозрачным цветом. Через документы я узнаю, что я могу создать сплошную кисть с помощью color.fromargb (). Но проблема в том, что я могу просто передать три параметра в color.fromargb (красный, зеленый, синий) вместо 4 параметров (альфа, красный, зеленый, синий). Так как я могу это исправить? Я работаю над компактным фреймворком 2.0. Заранее спасибо.

Ответы [ 2 ]

2 голосов
/ 11 января 2010

Компактный каркас поддерживает перегрузку , принимая только один параметр Int32 , представляющий 32-битное значение ARGB. Из этой статьи:

Порядок байтов 32-битного значения ARGB равен AARRGGBB.

Так что, если вы знаете свои значения R, G и B как байты, вы сможете создать из них желаемое значение. Что-то вроде:

var argb = (Int32)(128 | r << 16 | g << 8 | b);
var color = Color.FromArgb(argb);

... и, согласно комментарию @Andrew Cash ниже, вы можете сдвинуть альфа-значение влево на 24, если хотите настроить прозрачность.

Этот код не проверен, но вы поняли.

1 голос
/ 28 января 2010

Я думаю, вам понадобится P / Invoke AlphaBlend из API обработки изображений.

/// <summary>
/// The AlphaBlend function displays bitmaps that have transparent or semitransparent pixels.
/// </summary>
/// <param name="hdcDest">[in] Handle to the destination device context.</param>
/// <param name="xDest">[in] Specifies the x-coordinate, in logical units, of the upper-left corner of the destination rectangle.</param>
/// <param name="yDest">[in] Specifies the y-coordinate, in logical units, of the upper-left corner of the destination rectangle.</param>
/// <param name="cxDest">[in] Specifies the width, in logical units, of the destination rectangle.</param>
/// <param name="cyDest">[in] Specifies the height, in logical units, of the destination rectangle.</param>
/// <param name="hdcSrc">[in] Handle to the source device context.</param>
/// <param name="xSrc">[in] Specifies the x-coordinate, in logical units, of the upper-left corner of the source rectangle.</param>
/// <param name="ySrc">[in] Specifies the y-coordinate, in logical units, of the upper-left corner of the source rectangle.</param>
/// <param name="cxSrc">[in] Specifies the width, in logical units, of the source rectangle.</param>
/// <param name="cySrc">[in] Specifies the height, in logical units, of the source rectangle.</param>
/// <param name="blendFunction">[in] Specifies the alpha-blending function for source and destination bitmaps, a global alpha value to be applied to the entire source bitmap, and format information for the source bitmap. The source and destination blend functions are currently limited to AC_SRC_OVER. See the BLENDFUNCTION and EMRALPHABLEND structures.</param>
/// <returns>If the function succeeds, the return value is TRUE.  If the function fails, the return value is FALSE. </returns>
[DllImport("coredll.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool AlphaBlend(
    IntPtr hdcDest,
    int xDest,
    int yDest,
    int cxDest,
    int cyDest,
    IntPtr hdcSrc,
    int xSrc,
    int ySrc,
    int cxSrc,
    int cySrc,
    BlendFunction blendFunction);

BlendFunction определяется как:

/// <summary>
/// This structure controls blending by specifying the blending functions for source and destination bitmaps. 
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct BlendFunction
{
    /// <summary>
    /// Specifies the source blend operation. Currently, the only source and destination blend operation that has been defined is AC_SRC_OVER. For details, see the following Remarks section.
    /// </summary>
    public byte BlendOp;

    /// <summary>
    /// Must be zero.
    /// </summary>
    public byte BlendFlags;

    /// <summary>
    /// Specifies an alpha transparency value to be used on the entire source bitmap. The SourceConstantAlpha value is combined with any per-pixel alpha values in the source bitmap. If you set SourceConstantAlpha to 0, it is assumed that your image is transparent. When you only want to use per-pixel alpha values, set the SourceConstantAlpha value to 255 (opaque) .
    /// </summary>
    public byte SourceConstantAlpha;

    /// <summary>
    /// This member controls the way the source and destination bitmaps are interpreted. The following table shows the value for AlphaFormat. 
    /// ---
    /// AC_SRC_ALPHA   This flag is set when the bitmap has an Alpha channel (that is, per-pixel alpha). Because this API uses premultiplied alpha, the red, green and blue channel values in the bitmap must be premultiplied with the alpha channel value. For example, if the alpha channel value is x, the red, green and blue channels must be multiplied by x and divided by 0xff before the call. 
    /// </summary>
    public byte AlphaFormat;

    /// <summary>
    ///     Initializes a new instance of the <see cref="BlendFunction"/> structure.
    /// </summary>
    /// <param name="alphaConst">Specifies an alpha transparency value to be used on the entire source bitmap.
    /// </param>
    /// <param name="alphaFormat">Alpha flag
    /// </param>
    public BlendFunction(byte alphaConst, byte alphaFormat)
    {
        this.BlendOp = 0;
        this.BlendFlags = 0;
        this.SourceConstantAlpha = alphaConst;
        this.AlphaFormat = alphaFormat;
    }
}
...