Using the drawingAPI to create strokes
January 25th, 2007 . by polyGeek![]() |
Problem: if you use the drawingAPI to create a rectangle with a stroke then the stroke will be centered on the edges of the rectangle. That means if you are drawing a rectangle that is 50 pixels wide and has a stroke of 10 pixels then the visible width of the rectangle will be 60 pixels. The width of the containing MovieClip will also report 60 pixels.
visibleRectangle = rectangleWidth + strokeWidth/2
That’s probably not what you want.
I ran into this problem with the ZuneMediaPlayer at Zune.net. The panels needed to be created with the drawingAPI because they had to be skinable. Their color, alpha, strokeWidth are all contained as settings in XML. The artists wanted the panels to have a 2 pixel gap between them, simple enough. But some of the designs would have a border/stroke and others would not.
Plus, as you can see that if you have a thick stroke with less that full alpha then you’ll see the fill cutting across half of the stroke. Again, not very appealing.
I created a PerfectRectangle class to handle all the math conversions to produce what you would expect. You pass the strokeWidth, rectangleWidth/Height and it does the math so that the fill is drawn inside of the stroke and the width/height of the rectange ( fill and stroke ) will be the width/height that you pass.
I haven’t decided how to wrap this up in my framework yet so this class just stands alone. You can use it as is, extend it, or just use this as a starting point to wrap this into your own framework. I also did some experimenting in Flex and it gives the same results. I’ll work on an AS3 class to go along with this when I have time.
Below is a portion of the drawPanel method from the PerfectRectangle class.













Yeah, I have had similar issues where I swear I had all my math right and rounded off the pixels etc. etc. but still it’s freaking out and not appearing where I wanted. Ultimately, I think that sometimes you just have to use fills and masks etc. That is, make very very thin fills instead of strokes.
@Phillip: I always say, “go with what works.” I like writing elegant code as much as the next dev but ultimately, I have limited time and if I can mash some crap together that works then I call it a job well done and get on to the next thing.
Leave a Reply