Close Menu
geekfence.comgeekfence.com
    What's Hot

    HCLTech acquires HPE telco unit

    December 29, 2025

    This tiny chip could change the future of quantum computing

    December 29, 2025

    What’s In a Name? Mainframe GDGs Get the Job Done

    December 29, 2025
    Facebook X (Twitter) Instagram
    • About Us
    • Contact Us
    Facebook Instagram
    geekfence.comgeekfence.com
    • Home
    • UK Tech News
    • AI
    • Big Data
    • Cyber Security
      • Cloud Computing
      • iOS Development
    • IoT
    • Mobile
    • Software
      • Software Development
      • Software Engineering
    • Technology
      • Green Technology
      • Nanotechnology
    • Telecom
    geekfence.comgeekfence.com
    Home»iOS Development»Swift / CoreGraphics: semicircular arc draws correctly but arrow pointer position/rotation doesn’t match BMI value in exported PDF
    iOS Development

    Swift / CoreGraphics: semicircular arc draws correctly but arrow pointer position/rotation doesn’t match BMI value in exported PDF

    AdminBy AdminNovember 2, 2025No Comments5 Mins Read4 Views
    Facebook Twitter Pinterest LinkedIn Telegram Tumblr Email
    Swift / CoreGraphics: semicircular arc draws correctly but arrow pointer position/rotation doesn’t match BMI value in exported PDF
    Share
    Facebook Twitter LinkedIn Pinterest Email


    I’m drawing a semicircular BMI gauge in a PDF using UIGraphicsPDFRenderer and UIBezierPath. The colored arc and labels render correctly, but the arrow pointer (which should point to the arc position corresponding to the BMI value) appears in the wrong position/side or with the wrong rotation for the BMI I pass.

    I pasted the full function below. The arc looks fine, but when I call generateBMIGaugePDF(bmi: someValue) the arrow does not sit under (or point exactly to) the correct location on the arc — it may be offset, mirrored, or rotated incorrectly.

    What am I doing wrong? How should I compute the arrow position and rotation so the arrow always sits under the arc at the correct radial position and points to the arc location representing the BMI?

    Please find my function below.

    func generateBMIGaugePDF(
        bmi: Double,
        bmiMin: Double = 10,
        bmiMax: Double = 40,
        pageSize: CGSize = CGSize(width: 595, height: 842)
    ) -> URL? {
        let clampedBMI = max(min(bmi, bmiMax), bmiMin)
    
        let pdfMeta: [String: Any] = [
            kCGPDFContextAuthor as String: "YourApp",
            kCGPDFContextTitle as String: "BMI Gauge"
        ]
        let format = UIGraphicsPDFRendererFormat()
        format.documentInfo = pdfMeta
        let renderer = UIGraphicsPDFRenderer(bounds: CGRect(origin: .zero, size: pageSize), format: format)
        let filename = "bmi_gauge_\(Int(Date().timeIntervalSince1970)).pdf"
        let tempURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(filename)
    
        let margin: CGFloat = 40
        let center = CGPoint(x: pageSize.width / 2, y: pageSize.height / 2 - 30)
        let radius: CGFloat = min(pageSize.width - 2 * margin, pageSize.height / 2) / 2
        let lineWidth: CGFloat = 28
    
        // I draw the semicircle from right (0) to left (π)
        let startAngle = CGFloat(0)
        let endAngle = CGFloat.pi
        let totalAngle = endAngle - startAngle
    
        let segments = 3
        let segmentAngle = totalAngle / CGFloat(segments)
    
        let segmentColors: [UIColor] = [
            UIColor(red: 1.00, green: 0.56, blue: 0.20, alpha: 1.0),
            UIColor(red: 0.18, green: 0.86, blue: 0.40, alpha: 1.0),
            UIColor(red: 0.18, green: 0.55, blue: 0.98, alpha: 1.0)
        ]
    
        // angleForBMI - NOTE: I think this mapping may be related to the bug
        func angleForBMI(_ v: Double) -> CGFloat {
            let denom = bmiMax - bmiMin != 0 ? bmiMax - bmiMin : 1.0
            let t = CGFloat((v - bmiMin) / denom) // normalized 0..1
            // currently returning startAngle - t * totalAngle
            return startAngle - t * totalAngle
        }
    
        do {
            try renderer.writePDF(to: tempURL, withActions: { (context) in
                context.beginPage()
                let ctx = context.cgContext
                ctx.saveGState()
                ctx.setFillColor(UIColor.white.cgColor)
                ctx.fill(CGRect(origin: .zero, size: pageSize))
    
                // draw 3 colored arc segments
                for i in 0..<segments {
                    let segStart = startAngle - CGFloat(i) * segmentAngle
                    let segEnd = segStart - segmentAngle
                    let arcPath = UIBezierPath(arcCenter: center,
                                               radius: radius,
                                               startAngle: segEnd,
                                               endAngle: segStart,
                                               clockwise: true)
                    arcPath.lineWidth = lineWidth
                    arcPath.lineCapStyle = .butt
                    ctx.setStrokeColor(segmentColors[i % segmentColors.count].cgColor)
                    ctx.setLineWidth(lineWidth)
                    ctx.addPath(arcPath.cgPath)
                    ctx.strokePath()
                }
    
                // outline, labels, min/max, center text ... (omitted for brevity in this paste)
    
                // Draw arrow (pointer) below arc
                let pointerAngle = angleForBMI(clampedBMI) // computed angle on arc (radians)
                let pointerLength: CGFloat = radius * 0.9
    
                // I originally set the arrow base like this:
                let arrowBaseCenter = CGPoint(x: center.x, y: center.y + radius + 40)
    
                // Then I tried to rotate the arrow like this:
                ctx.saveGState()
                // <-- I tried this and variants (translate y/3, translate center, rotate +pi, etc.)
                ctx.translateBy(x: arrowBaseCenter.x, y: arrowBaseCenter.y / 3)
                let initialArrowAngle: CGFloat = -CGFloat.pi / 2
                ctx.rotate(by: pointerAngle - initialArrowAngle)
    
                // Draw stem
                let stemWidth: CGFloat = 6
                let stemHeight: CGFloat = 28
                let stemRect = CGRect(x: -stemWidth / 2, y: 0, width: stemWidth, height: stemHeight)
                ctx.setFillColor(UIColor.black.cgColor)
                ctx.addRect(stemRect)
                ctx.drawPath(using: .fill)
    
                // Draw triangle tip (tip at negative Y)
                let trianglePath = UIBezierPath()
                trianglePath.move(to: CGPoint(x: 0, y: -pointerLength * 0.18))
                trianglePath.addLine(to: CGPoint(x: -12, y: 0))
                trianglePath.addLine(to: CGPoint(x: 12, y: 0))
                trianglePath.close()
                ctx.setFillColor(UIColor.black.cgColor)
                ctx.addPath(trianglePath.cgPath)
                ctx.drawPath(using: .fill)
    
                ctx.restoreGState()
                ctx.restoreGState()
            })
    
            return tempURL
        } catch {
            print("Failed to generate BMI gauge PDF: \(error)")
            return nil
        }
    }
    
    

    Observed behaviour

    The arc and colored segments draw correctly and consistently.

    The arrow angle sometimes matches (i.e. the arrow visually rotates) but the arrow base is misplaced (often on the opposite side or shifted), so it does not point to the actual position on the arc corresponding to the BMI value.

    I’ve tried quick fixes like changing translate coordinates (arrowBaseCenter.y / 3 vs arrowBaseCenter.y), adding + .pi to the rotation, changing initialArrowAngle, etc. Nothing reliably positions the arrow at the correct x/y for given BMI values.

    What I expect

    For any BMI value (within range), the arrow should:

    be drawn with its base located just outside the arc at the radial position that corresponds to that BMI (so horizontal/vertical position depends on the BMI),

    and be rotated so its tip points precisely to the arc point corresponding to the BMI.

    What I tried

    Changing ctx.translateBy values.

    ctx.rotate(by: pointerAngle – CGFloat.pi/2) and variants like adding + .pi.

    Calculating arrow base using center.x + cos(pointerAngle) * something — but I couldn’t get the rotation & placement to align reliably.

    Clamping BMI values — not relevant to the geometry but done.

    i want this type of result

    Swift / CoreGraphics: semicircular arc draws correctly but arrow pointer position/rotation doesn’t match BMI value in exported PDF



    Source link

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email

    Related Posts

    Designing custom UI with Liquid Glass on iOS 26 – Donny Wals

    December 29, 2025

    SwiftText | Cocoanetics

    December 28, 2025

    Uniquely identifying views – The.Swift.Dev.

    December 27, 2025

    Unable to upload my app with Transporter. Some kind of version mismatch? [duplicate]

    December 26, 2025

    Experimenting with Live Activities – Ole Begemann

    December 25, 2025

    Announcing Mastering SwiftUI for iOS 18 and Xcode 16

    December 24, 2025
    Top Posts

    Understanding U-Net Architecture in Deep Learning

    November 25, 20258 Views

    Microsoft 365 Copilot now enables you to build apps and workflows

    October 29, 20258 Views

    Here’s the latest company planning for gene-edited babies

    November 2, 20257 Views
    Don't Miss

    HCLTech acquires HPE telco unit

    December 29, 2025

    HCLTech moves toward a future of AI-driven growth In sum – what we know: The…

    This tiny chip could change the future of quantum computing

    December 29, 2025

    What’s In a Name? Mainframe GDGs Get the Job Done

    December 29, 2025

    Microsoft named a Leader in Gartner® Magic Quadrant™ for AI Application Development Platforms

    December 29, 2025
    Stay In Touch
    • Facebook
    • Instagram
    About Us

    At GeekFence, we are a team of tech-enthusiasts, industry watchers and content creators who believe that technology isn’t just about gadgets—it’s about how innovation transforms our lives, work and society. We’ve come together to build a place where readers, thinkers and industry insiders can converge to explore what’s next in tech.

    Our Picks

    HCLTech acquires HPE telco unit

    December 29, 2025

    This tiny chip could change the future of quantum computing

    December 29, 2025

    Subscribe to Updates

    Please enable JavaScript in your browser to complete this form.
    Loading
    • About Us
    • Contact Us
    • Disclaimer
    • Privacy Policy
    • Terms and Conditions
    © 2025 Geekfence.All Rigt Reserved.

    Type above and press Enter to search. Press Esc to cancel.