# Example O1: Scale bar

The following script renders a scale bar into the viewport (with a fixed length of 4 nm, as shown in the example picture). You can copy/paste the source code into the script input field and adjust the parameters in the code as needed.

    from ovito.qt_compat import QtCore
    from ovito.qt_compat import QtGui

    # Parameters:
    bar_length = 40   # Simulation units (e.g. Angstroms)
    bar_color = QtGui.QColor(0,0,0)
    label_text = f"{bar_length/10} nm"
    label_color = QtGui.QColor(255,255,255)

    # This function is called by OVITO on every viewport update.
    def render(args):
        if args.is_perspective:
            raise Exception("This overlay only works with non-perspective viewports.")

        # Compute length of bar in screen space
        screen_length = args.project_size((0,0,0), bar_length)

        # Define geometry of bar in screen space
        height = 0.07 * args.painter.window().height()
        margin = 0.02 * args.painter.window().height()
        rect = QtCore.QRectF(margin, margin, screen_length, height)

        # Render bar rectangle
        args.painter.fillRect(rect, bar_color)

        # Render text label
        font = args.painter.font()
        font.setPixelSize(height)
        args.painter.setFont(font)
        args.painter.setPen(QtGui.QPen(label_color))
        args.painter.drawText(rect, QtCore.Qt.AlignCenter, label_text)