【问题标题】:draw a shape with QPainterPath having a border strictly on the inside of the shape使用 QPainterPath 绘制一个形状,边界严格位于形状的内部
【发布时间】:2023-02-16 08:04:24
【问题描述】:

简而言之,当我使用 QPainter 和一支宽度为例如penWidth = 10.0 然后边框宽度的一半实际上画在形状区域的外面,一半画在里面。

但是,我想用笔绘制一个形状,使边框仅位于形状区域的内部。

我可能可以使用这个技巧:我将笔的宽度设置为两倍大,并且还设置了剪切路径,以便剪切掉边界线的外半部分,只保留边界线的内半部分。

例子:

QColor penColor(Qt::red);
qreal penWidth = 5.0;
QPainterPath shape;
// ...here I define the shape

QPainter painter(device);

// the trick comes here
QPen p(penColor, penWidth * 2); // we make the border pen twice as thick
painter.setClipPath(path); // and we clip the outer half of the border away

// now let's paint it
painter.drawPath(shape);

我认为这可能不是最有效的方法,因为裁剪可能是非常昂贵的操作。

有没有其他更优雅的方式?

【问题讨论】:

    标签: c++ qt


    【解决方案1】:

    是的,您可以将您的笔宽的一半添加到您的 x 和 y 坐标,然后从您的形状大小中减去完整的笔宽……(减去整个笔宽,因为您的笔宽的一半会改变 xy 坐标)。

    但您也可以使用 QRectF::adjusted(qreal dx1, qreal dy1, qreal dx2, qreal dy2) 。这里减少了rect,要输入的值与上面的例子略有不同。

    void Widget::paintEvent(QPaintEvent *)
    {
        QPainter painter(this);
        qreal penWidth = 20;
    
        painter.setPen(QPen(Qt::red, penWidth));
        QPainterPath path;
    
    //    path.addEllipse(rect().left() + (penWidth/2),         // x: coordinate + (pen width / 2)
    //                    rect().top() + (penWidth/2),          // y: coordinate + (pen width / 2)
    //                    rect().size().width() - penWidth,     // width - penwidth
    //                    rect().size().height() - penWidth);   // height - penwidth
        // or:
        path.addEllipse(rect().adjusted(penWidth/2,penWidth/2, -(penWidth/2),-(penWidth/2)));
        painter.drawPath(path);
    }
    
    

    【讨论】:

      猜你喜欢
      • 2020-05-10
      • 1970-01-01
      • 1970-01-01
      • 2016-11-24
      • 2017-12-10
      • 2021-09-19
      • 2018-04-26
      • 2012-11-21
      • 2012-07-09
      相关资源
      最近更新 更多