swift中自定义图像边界

时间:2015-04-20 18:35:05

标签: ios swift boundary

我想将此图像的边界从矩形转换为六边形。 我知道如何为按钮实现自定义边界。但是如何为图像实现它?

点击一个图像的一角时,相邻的图像被轻敲。

以下是点按识别器的代码段,用于检测图像的边界并相应地执行某些操作。

import UIKit
class Game: UIViewController {
    var flag:Bool! = false
@IBOutlet var fields: [SIXImageView]!
 var currentPlayer:String!

override func viewDidLoad() {
    super.viewDidLoad()
 setupField ()

}

    // Do any additional setup after loading the view.


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

func fieldTapped (recognizer:UITapGestureRecognizer){
    let tappedField  = recognizer.view as SIXImageView
    tappedField.setPlayer(currentPlayer)

    let messageDict = ["field":tappedField.tag, 
    "player":currentPlayer]}


 func setupField () {
     currentPlayer = "x"
    for index in 0 ... fields.count - 1{
        let gestureRecognizer = UITapGestureRecognizer(target: self, action: "fieldTapped:")
        gestureRecognizer.numberOfTapsRequired = 1
        fields[index].addGestureRecognizer(gestureRecognizer)
        checkResults()
    }


}

Image having square boundary

Image having square boundary

1 个答案:

答案 0 :(得分:0)

您可以使用以下代码将UIImageView从矩形转换为六边形:

var rect = image.frame
var hexagonMask = CAShapeLayer()
var hexagonBorder = CAShapeLayer()
hexagonBorder.frame = image.layer.bounds

var hexagonPath = UIBezierPath()
var sideWidth : CGFloat = 2 * ( 0.5 * rect.size.width / 2 )
var lcolumn = ( rect.size.width - sideWidth ) / 2

var rcolumn : CGFloat = rect.size.width - lcolumn;
var height : CGFloat = 0.966025 * rect.size.height;
var y : CGFloat = (rect.size.height - height) / 2;
var by : CGFloat = rect.size.height - y;
var midy : CGFloat = rect.size.height / 2;
var rightmost : CGFloat = rect.size.width;


hexagonPath.moveToPoint(CGPointMake(lcolumn, y))
hexagonPath.addLineToPoint(CGPointMake(rcolumn, y))
hexagonPath.addLineToPoint(CGPointMake(rightmost, midy))
hexagonPath.addLineToPoint(CGPointMake(rcolumn, by))
hexagonPath.addLineToPoint(CGPointMake(lcolumn, by))
hexagonPath.addLineToPoint(CGPointMake(0, midy))
hexagonPath.addLineToPoint(CGPointMake(lcolumn, y))

hexagonMask.path = hexagonPath.CGPath
hexagonBorder.path = hexagonPath.CGPath
hexagonBorder.fillColor = UIColor.clearColor().CGColor
hexagonBorder.strokeColor = UIColor.blackColor().CGColor
hexagonBorder.lineWidth = 5

image.layer.mask = hexagonMask
image.layer.cornerRadius = 10
image.layer.masksToBounds = true
image.layer.addSublayer(hexagonBorder)

您可以使用heightwidth等的值。 我希望这能帮到你。