0

I have the following draw(_ rect: CGRect) function

 override public func draw(_ rect: CGRect) {
        super.draw(rect)
     
        for (i, time) in times.enumerated() {
            let fontSize = style.font.pointSize
            let timeRect = CGRect(x: 2, y: y,
                                  width: style.leftInset, height: fontSize)
            let timeString = NSString(string: time)
            timeString.draw(in: timeRect, withAttributes: attributes)
            
        }
    }

In some scenarios I want to remove all the previous drawed NSString objects from the UIView and redraw again. But it seems there is no API to do that?

Can anyone help?

update

When setNeedsDisplay is called the UIView gets rid of all it's previous drawings. But for some reason after the second time I call the drawRect method my strings gets fuzzy.

Before After the first drawRect

After After the second drawRect

Steaphann
  • 2,797
  • 6
  • 50
  • 109
  • 1
    https://stackoverflow.com/questions/25360303/uiview-draw-rect-retains-the-previous-drawing-and-does-not-clear-on-view-transf ? But is `times` cleaned in the mean time? Else a `setNeedsDisplay` might be enough. – Larme Jun 07 '21 at 09:37
  • Times is an array of strings, I check if this array is changed and only then I call the drawRect again. The drawed strings are fuzzy after the drawRect is finished so I guess the previous ones are still there. – Steaphann Jun 07 '21 at 10:01
  • Where does a guy named 'attributes' come from? – El Tomato Jun 07 '21 at 11:49
  • @ElTomato it is defined above in the class. – Steaphann Jun 07 '21 at 13:41
  • Does this answer your question? "[Painting on CGContextRef on Retina display](https://stackoverflow.com/q/17637840/90527)", "[iOS drawing in CALayers drawInContext is either pixelated or blurry on retina](https://stackoverflow.com/q/25746368/90527)", "[Views drawn from code (PaintCode) are pixelated, very pixelated when scaled](https://stackoverflow.com/q/42978322/90527)" – outis Sep 09 '21 at 19:59

1 Answers1

1

As with Objective-C, there's no need to explicitly remove the drawn elements. Instead, call setNeedsDisplay(_:) to invalidate the area you want redrawn, and your UIView's draw(_:) method will be called to redraw the strings. This is explained in the "View Drawing Cycle" section of UIView's documentation.

outis
  • 75,655
  • 22
  • 151
  • 221
  • Okay so the strings are not going to be drawn twice, I've added some screenshots to my question to make it more clear what is happening. Do you have any idea what's causing this ? – Steaphann Jun 08 '21 at 08:37
  • 1
    @Steaphann: that's a different question, and should be posted as such (after searching for existing questions), even if that's what you were trying to ask about originally (which shows the value of including the overall issue in the question, not just the specific attempted solution). – outis Jun 23 '21 at 07:16