简体   繁体   English

在paintComponent中重绘形状时无法保存描边/线条粗细

[英]Can't save Stroke/Line Thickness when redrawing Shapes in paintComponent

I've been working on a simple paint program and I have recently run into a snag when redrawing shapes in my paint component. 我一直在开发一个简单的绘画程序,最近在绘画组件中重新绘制形状时遇到了麻烦。

 @Override
    public void paintComponent(final Graphics theGraphics) {
        super.paintComponent(theGraphics);       
        final Graphics2D g2d = (Graphics2D) theGraphics;



    if (!preDrawnShapes.isEmpty() && !preDrawnShapeThickness.isEmpty()) {
        for (int i = 0; i < preDrawnShapes.size(); i++) {
            g2d.setStroke(new BasicStroke(preDrawnShapeThickness.get(i)));

            g2d.draw(preDrawnShapes.get(i));

        } 
    }

    g2d.setStroke(new BasicStroke(currentThickness));


    if (myShape != null) {

        g2d.draw(myShape);
        preDrawnShapeThickness.add(currentThickness);

    }


}

This paintComponenent is supposed to first redraw the shapes previously drawn before before then drawing the new shape created from user input. 此paintComponenent应该首先重绘之前绘制的形状,然后再绘制通过用户输入创建的新形状。

For some reason, the shape thickness when drawing the new shape is set to the current thickness but any shape that I drew before had a default thickness of 1. 由于某种原因,绘制新形状时的形状厚度设置为当前厚度,但是我之前绘制的任何形状的默认厚度均为1。

在此处输入图片说明

preDrawnShapes is a Shapes ArrayList and preDrawnShapeThickiness is a Float Arraylist. preDrawnShapes是Shapes ArrayList,preDrawnShapeThickiness是Float Arraylist。

Am I missing something here? 我在这里想念什么吗?

UPDATE: I've discovered that PreDrawnShapeThickness stores only Floats of zero. 更新:我发现PreDrawnShapeThickness仅存储零的浮点数。 I am unsure why. 我不确定为什么。

There are two common ways to do incremental painting: 有两种常见的方式来进行增量绘制:

  1. Keep a List of Objects that you want to paint. 保留要绘制的对象列表。 Then the paintComponent() method iterates through the List and paints each object. 然后paintComponent()方法遍历List并绘制每个对象。 So in your case the custom object would contain the Shape you want to paint and an int value for the thickness of the shape. 因此,在您的情况下,自定义对象将包含要绘制的Shape以及该Shape的厚度的int值。

  2. Just paint each Object directly to a BufferedImage. 只需将每个对象直接绘制到BufferedImage即可。 Then you can just use a JLabel to display the BufferedImage as an Icon, or do custom painting to paint the BufferedImage. 然后,您可以仅使用JLabel将BufferedImage显示为图标,或者进行自定义绘制以绘制BufferedImage。

Check out Custom Painting Approaches for examples of both approaches. 查看“ 自定义绘画方法”以获取这两种方法的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM