//切割图片的某一部分
func clipImage(_ oldImage:UIImage, frame: CGRect) -> UIImage {
let cgImage = oldImage.cgImage!.cropping(to: frame)
let image = UIImage(cgImage: cgImage!)
return image
}
切图 代码
import UIKit
class ViewController: UIViewController {
//上一次点击的图片
var lastImageView: UIImageView?
//属性 存值
override func viewDidLoad() {
super.viewDidLoad()
//加载图片
let path = Bundle.main.path(forResource: "king2", ofType: "png")
let kingImage = UIImage(contentsOfFile: path!)
for i in 0..<3{
//i表示行
for j in 0..<3{
//j表示列
// let frame = CGRect(x: 100*CGFloat(j)+100, y: 100*CGFloat(i)+150, width: 100, height: 100)
let frame = CGRect(x: CGFloat(100*j), y: CGFloat(100*i), width: 100, height: 100)
let currentImage = clipImage(kingImage!, frame: frame)
let imageView = UIImageView(frame: CGRect(x: CGFloat(100*(j)+10), y: CGFloat(100*(i+1)), width: 100, height: 100))
if i==2 && j==2 {
//最后一个是没有图片
}else {
imageView.image = currentImage
imageView.layer.borderWidth = 2
imageView.layer.borderColor = UIColor.yellow.cgColor
}
imageView.isUserInteractionEnabled = true
//添加手势
let gesture = UITapGestureRecognizer(target: self, action: #selector(changePosition(gesture:)) )
//let g = UITapGestureRecognizer(target: self, action: #selector(tapAction(_:)))
// selector 变了
imageView.addGestureRecognizer(gesture)
view.addSubview(imageView)
}
}
}
func changePosition(gesture: UIGestureRecognizer){
let currentImageView = gesture.view as! UIImageView
//第一次点击
if lastImageView == nil {
lastImageView = currentImageView
}else {//第二次点击
// if lastImageView == nil || currentImageView == nil {
//至少有一个是空白
if lastImageView?.image == nil || currentImageView.image == nil {
//所以是 view.image
//空白的只能和相邻的进行交换
//计算中心点的距离
let distanceX = fabs((lastImageView?.frame.origin.x)! - currentImageView.frame.origin.x)
let distanceY = fabs((lastImageView?.frame.origin.y)! - currentImageView.frame.origin.y)
if (distanceX>1 && distanceY<101)||(distanceY>1 && distanceX<101){
//相邻
//交换
let frame = currentImageView.frame
currentImageView.frame = (lastImageView?.frame)!
lastImageView?.frame = frame
}
}
lastImageView = nil
}
}
/* 我写的 ,没有添加 相邻图片中 一方必须为空
func changePosition(gesture: UIGestureRecognizer){
if (lastImageView == nil){
lastImageView = gesture.view as! UIImageView?
}else {
let frame = gesture.view?.frame
let distanceX = (frame?.origin.x)! - (lastImageView?.frame.origin.x)!
let disX = distanceX>0 ? distanceX : -distanceX
let distanceY = (frame?.origin.y)! - (lastImageView?.frame.origin.y)!
let disY = distanceY>0 ? distanceY : -distanceY
if (99-disX)*(disY-99)>0{
gesture.view?.frame = (lastImageView?.frame)!
lastImageView?.frame = frame!
}
lastImageView = nil
}
}
*/
//切割图片的某一部分
func clipImage(_ oldImage: UIImage, frame: CGRect) -> UIImage{
let theCGImage = oldImage.cgImage!.cropping(to: frame)
let image = UIImage(cgImage: theCGImage!)
return image
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}