locked
Drawing Images and Text on a Control RRS feed

  • Question

  • Hi Everyone,

    A project I'm working on has involved the creation of a custom button that includes an image and two captions (different fonts). Depending on the height of the control, either only one line of text is shown, both lines are shown, or both and the icon are shown, ie;

    (one line)
    --------
    | aaaa |
    --------

    (two lines)
    --------
    | aaaaa|
    | bbbbb|
    ---------

    (two lines and one icon)
    --------
    | ICON |
    | ICON |
    | aaaaa |
    | bbbbb |
    --------

    Anyhow, for the prototyping I just used a table layout panel, labels and a picture box with some code the hide certain table rows as required, works like a charm. I'm now implementing this, and the prototype approach is awefully slow drawing (as expected) if I have multiple buttons on screen. So now I'm just drawing all the elements to the control when it's painted, but I'm having a hard time figuring out how to get the dimensions of the text which are required for centering. I'm using

    StringFormat format = new StringFormat();
    Region[] r = g.MeasureCharacterRanges("AAAAAA", lblPrimary.Font, new Rectangle(0, 0, 1000, 1000), format);
    RectangleF rect = r[0].GetBounds(g);

    but getting an index out of range when trying to access r[0].

    So I've got two questions,

    1: Any idea why MeasureCharacterRanges() is returning an empty array and
    2: Is there any better (and preferably simpler) way to efficiently implement this control (rather than manually finding sizes of everything, resizing, and then centering and drawing)?

    As always any input is appreciated :)

    Monday, February 8, 2010 9:48 AM

Answers

  • You should have to get the size of the stuff for every draw, it'll only change when the font changes or the Icon is changed.
    The reason your call fails is because you have set the character ranges as per the examples here: http://msdn.microsoft.com/en-us/library/system.drawing.graphics.measurecharacterranges.aspx

    You may be wanting the MeasureString method which measures the whole string passed.



    HTH Ciaran http://wannabedeveloper.spaces.live.com
    • Marked as answer by Aland Li Wednesday, February 10, 2010 10:46 AM
    Monday, February 8, 2010 12:08 PM