Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make UILabel at 45 degree with a cross background colour swift

I want to display a text at 45 degree with a background color.

Example

like this

Thanks in advance

like image 635
Parth Dhorda Avatar asked Sep 01 '25 22:09

Parth Dhorda


1 Answers

This element contains two sub-elements:

  1. triangle UIView;
  2. rotated UILabel.

First can be achieved by creating custom view with override draw method:

class TriangleView: UIView {

    override func draw(_ rect: CGRect) {
        let path = UIBezierPath()
        path.move(to: .zero)
        path.addLine(to: CGPoint(x: rect.maxX, y: 0))
        path.addLine(to: CGPoint(x: 0, y: rect.maxY))
        path.close()

        UIColor.red.withAlphaComponent(0.5).setFill()
        path.fill()
    }

}

The second is simple transform rotation for -45 degree:

label.transform = CGAffineTransform(rotationAngle: -.pi / 4)

Result:

enter image description here

Next thing you should manage – precisely set UILabel bounds (label shouldn't go away from the screen) and lines count. Constraints and attributed inspector for UILabel element can help you.

like image 97
pacification Avatar answered Sep 04 '25 00:09

pacification