How to remove “stretch marks” on custom button border?

非 Y 不嫁゛ 提交于 2019-12-01 06:10:58

问题


When performing some custom painting on a button's Graphics2D object, I get the following results:

The leftmost button is untoggled and the other is toggled. As you can see, the toggled button has these white "stretch marks." Why are these there and how do I remove them?

And here is the code I use to draw the border:

// Draw border of button
if(!getModel().isSelected())
{
    g2.fillRoundRect(2, 2, getWidth() - 5, getHeight() - 5, ARC_WIDTH, ARC_HEIGHT);
    g2.setColor(Color.BLACK);
    g2.drawRoundRect(0, 0, getWidth() - 1, getHeight() - 1, ARC_WIDTH, ARC_HEIGHT);
    g2.setColor(Color.WHITE);
    g2.drawRoundRect(1, 1, getWidth() - 3, getHeight() - 3, ARC_WIDTH, ARC_HEIGHT);
    g2.setColor(Color.WHITE);
    g2.drawRoundRect(2, 2, getWidth() - 5, getHeight() - 5, ARC_WIDTH, ARC_HEIGHT);
    g2.setColor(Color.BLACK);
    g2.drawRoundRect(3, 3, getWidth() - 7, getHeight() - 7, ARC_WIDTH, ARC_HEIGHT);
}
else
{
    g2.fillRoundRect(2, 2, getWidth() - 5, getHeight() - 5, ARC_WIDTH, ARC_HEIGHT);
    g2.setColor(Color.BLACK);
    g2.drawRoundRect(0, 0, getWidth() - 1, getHeight() - 1, ARC_WIDTH, ARC_HEIGHT);
    g2.setColor(Color.BLACK);
    g2.drawRoundRect(1, 1, getWidth() - 3, getHeight() - 3, ARC_WIDTH, ARC_HEIGHT);
    g2.setColor(Color.BLACK);
    g2.drawRoundRect(2, 2, getWidth() - 5, getHeight() - 5, ARC_WIDTH, ARC_HEIGHT);
    g2.setColor(Color.BLACK);
    g2.drawRoundRect(3, 3, getWidth() - 7, getHeight() - 7, ARC_WIDTH, ARC_HEIGHT);
}

回答1:


Why are you drawing so many rounded rectangles around the button? As far as I can see, the correct way to do this would be to use setStroke() API while drawing the kind of border you like.




回答2:


it's because you draw if by drawing several 1px thick borders which misses some pixels in the arcs (draw it again with different colors and zoom in on the image to see it)

use the fill to set the color of the border and then draw the contrasting borders

Color fillcolor = Color.WHITE;
Color bordercolor = Color.BLACK;

if(getModel().isSelected())
{
    fillcolor = Color.BLACK;
}
//fill the full rectangle
g2.setColor(fillcolor);
g2.fillRoundRect(0, 0, getWidth() - 1, getHeight() - 1, ARC_WIDTH, ARC_HEIGHT);

//draw contrasted borders
g2.setColor(bordercolor);
g2.drawRoundRect(0, 0, getWidth() - 1, getHeight() - 1, ARC_WIDTH, ARC_HEIGHT);
g2.setColor(bordercolor);
g2.drawRoundRect(3, 3, getWidth() - 7, getHeight() - 7, ARC_WIDTH, ARC_HEIGHT);


来源:https://stackoverflow.com/questions/9382426/how-to-remove-stretch-marks-on-custom-button-border

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!