Swift: rotate oblique a button in iOS8?

2019-09-06 07:36发布

问题:

Let's say I have one or more 100*50 rectangular buttons on my ViewController.

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib. 

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func myButton(sender: UIButton) {
    }

}

usually I put my graphic images as their image. then I apply auto layout.

BUT! I need them to be oblique not horizontal, I.E. if you have a square, I need to rotate it to be a diamond (45°), it's the same. I know it's not possible via interface builder. how to make it by code?

maybe I should use CGAffineTransformRotate or RotateTranform but I really don't know how to start

回答1:

The best way to is rotate the views layer, CGAffineTransformMakeTranslation indicates the point in the layer where the layer will rotate around, remember layers go from (0,0) to (1.1) so the middle is (0.5, 0.5):

    var transform = CGAffineTransformMakeTranslation(0.5, 0.5)
    var angle = CGFloat(M_PI / 2.0) //90 degress rotation
    transform = CGAffineTransformRotate(transform, angle)
    button.transform = transform

    button.layer.rasterizationScale = UIScreen.mainScreen().scale
    button.layer.shouldRasterize = true

    button.setNeedsDisplay()