Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Convert CornerRadius project to Swift 4. #10

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CornerRadius/CornerRadius.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -423,6 +423,7 @@
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_OBJC_BRIDGING_HEADER = "CornerRadius/CornerRadius-Bridging-Header.h";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 4.0;
};
name = Debug;
};
Expand All @@ -436,6 +437,7 @@
PRODUCT_BUNDLE_IDENTIFIER = NEU.CornerRadius;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_OBJC_BRIDGING_HEADER = "CornerRadius/CornerRadius-Bridging-Header.h";
SWIFT_VERSION = 4.0;
};
name = Release;
};
Expand Down
14 changes: 6 additions & 8 deletions CornerRadius/CornerRadius/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,31 +13,29 @@ class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?


func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
return true
}

func applicationWillResignActive(application: UIApplication) {
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

func applicationDidEnterBackground(application: UIApplication) {
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

func applicationWillEnterForeground(application: UIApplication) {
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(application: UIApplication) {
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(application: UIApplication) {
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

Expand Down
22 changes: 11 additions & 11 deletions CornerRadius/CornerRadius/CustomTableViewCell.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,18 @@ import UIKit

class CustomTableViewCell: UITableViewCell {

let imgView1 = UIImageView(frame: CGRectMake(5, 10, 20, 21))
let imgView2 = UIImageView(frame: CGRectMake(55, 10, 20, 21))
let view = UIView(frame: CGRectMake(150,10,40,21))
let label = UILabel(frame: CGRectMake(250,10,80,21))
let imgView1 = UIImageView(frame: CGRect(x: 5, y: 10, width: 20, height: 21))
let imgView2 = UIImageView(frame: CGRect(x: 55, y: 10, width: 20, height: 21))
let view = UIView(frame: CGRect(x: 150, y: 10, width: 40, height: 21))
let label = UILabel(frame: CGRect(x: 250, y: 10, width: 80, height: 21))

override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)

self.contentView.addSubview(imgView1)
self.contentView.addSubview(imgView2)

view.backgroundColor = UIColor.brownColor()
view.backgroundColor = UIColor.brown
view.layer.cornerRadius = 5

self.contentView.addSubview(view)
Expand All @@ -30,7 +30,7 @@ class CustomTableViewCell: UITableViewCell {
// label.kt_addCorner(radius: 8)
label.layer.cornerRadius = 5
label.text = "123"
label.backgroundColor = UIColor.brownColor()
label.backgroundColor = UIColor.brown
self.contentView.addSubview(label)
}

Expand All @@ -43,18 +43,18 @@ class CustomTableViewCell: UITableViewCell {
// Initialization code
}

func setupContent(imgName imgName: String) {
func setupContent(imgName: String) {
imgView1.image = UIImage(named: imgName)
imgView2.image = UIImage(named: imgName)

// 下面两行取消注释后试试
// imgView1.kt_addCorner(radius: 5)
// imgView2.kt_addCorner(radius: 5)
// imgView1.kt_imageViewAddCorner(radius: 5)
// imgView2.kt_imageViewAddCorner(radius: 5)
}

override func setSelected(selected: Bool, animated: Bool) {
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)

// Configure the view for the selected state
}

Expand Down
94 changes: 58 additions & 36 deletions CornerRadius/CornerRadius/KtCorner.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,25 +9,25 @@
import Foundation
import UIKit

private func roundbyunit(num: Double, inout _ unit: Double) -> Double {
private func roundbyunit(_ num: Double, _ unit: inout Double) -> Double {
let remain = modf(num, &unit)
if (remain > unit / 2.0) {
return ceilbyunit(num, &unit)
} else {
return floorbyunit(num, &unit)
}
}
private func ceilbyunit(num: Double, inout _ unit: Double) -> Double {
private func ceilbyunit(_ num: Double, _ unit: inout Double) -> Double {
return num - modf(num, &unit) + unit
}

private func floorbyunit(num: Double, inout _ unit: Double) -> Double {
private func floorbyunit(_ num: Double, _ unit: inout Double) -> Double {
return num - modf(num, &unit)
}

private func pixel(num: Double) -> Double {
var unit: Double
switch Int(UIScreen.mainScreen().scale) {
switch Int(UIScreen.main.scale) {
case 1: unit = 1.0 / 1.0
case 2: unit = 1.0 / 2.0
case 3: unit = 1.0 / 3.0
Expand All @@ -37,50 +37,60 @@ private func pixel(num: Double) -> Double {
}

extension UIView {
func kt_addCorner(radius radius: CGFloat) {
self.kt_addCorner(radius: radius, borderWidth: 1, backgroundColor: UIColor.clearColor(), borderColor: UIColor.blackColor())
func kt_addCorner(radius: CGFloat) {
self.kt_addCorner(radius: radius, borderWidth: 1, backgroundColor: UIColor.clear, borderColor: UIColor.black)
}

func kt_addCorner(radius radius: CGFloat,
func kt_addCorner(radius: CGFloat,
borderWidth: CGFloat,
backgroundColor: UIColor,
borderColor: UIColor) {
let imageView = UIImageView(image: kt_drawRectWithRoundedCorner(radius: radius,
borderWidth: borderWidth,
backgroundColor: backgroundColor,
borderColor: borderColor))
self.insertSubview(imageView, atIndex: 0)
borderWidth: borderWidth,
backgroundColor: backgroundColor,
borderColor: borderColor))
self.insertSubview(imageView, at: 0)
}

func kt_drawRectWithRoundedCorner(radius radius: CGFloat,
func kt_drawRectWithRoundedCorner(radius: CGFloat,
borderWidth: CGFloat,
backgroundColor: UIColor,
borderColor: UIColor) -> UIImage {
let sizeToFit = CGSize(width: pixel(Double(self.bounds.size.width)), height: Double(self.bounds.size.height))
let sizeToFit = CGSize(width: pixel(num: Double(self.bounds.size.width)), height: Double(self.bounds.size.height))
let halfBorderWidth = CGFloat(borderWidth / 2.0)

UIGraphicsBeginImageContextWithOptions(sizeToFit, false, UIScreen.mainScreen().scale)
let context = UIGraphicsGetCurrentContext()

CGContextSetLineWidth(context, borderWidth)
CGContextSetStrokeColorWithColor(context, borderColor.CGColor)
CGContextSetFillColorWithColor(context, backgroundColor.CGColor)
UIGraphicsBeginImageContextWithOptions(sizeToFit, false, UIScreen.main.scale)
guard let context = UIGraphicsGetCurrentContext() else {
UIGraphicsEndImageContext()
return UIImage()
}
context.setLineWidth(borderWidth)
context.setStrokeColor(borderColor.cgColor)
context.setFillColor(backgroundColor.cgColor)

let width = sizeToFit.width, height = sizeToFit.height
CGContextMoveToPoint(context, width - halfBorderWidth, radius + halfBorderWidth) // 开始坐标右边开始
CGContextAddArcToPoint(context, width - halfBorderWidth, height - halfBorderWidth, width - radius - halfBorderWidth, height - halfBorderWidth, radius) // 右下角角度
CGContextAddArcToPoint(context, halfBorderWidth, height - halfBorderWidth, halfBorderWidth, height - radius - halfBorderWidth, radius) // 左下角角度
CGContextAddArcToPoint(context, halfBorderWidth, halfBorderWidth, width - halfBorderWidth, halfBorderWidth, radius) // 左上角
CGContextAddArcToPoint(context, width - halfBorderWidth, halfBorderWidth, width - halfBorderWidth, radius + halfBorderWidth, radius) // 右上角

CGContextDrawPath(UIGraphicsGetCurrentContext(), .FillStroke)
context.move(to: CGPoint(x: width - halfBorderWidth, y: radius + halfBorderWidth)) // 开始坐标右边开始
context.addArc(tangent1End: CGPoint(x: width - halfBorderWidth, y: height - halfBorderWidth),
tangent2End: CGPoint(x: width - radius - halfBorderWidth, y: height - halfBorderWidth),
radius: radius) // 右下角
context.addArc(tangent1End: CGPoint(x: halfBorderWidth, y: height - halfBorderWidth),
tangent2End: CGPoint(x: halfBorderWidth, y: height - radius - halfBorderWidth),
radius: radius) // 左下角
context.addArc(tangent1End: CGPoint(x: halfBorderWidth, y: halfBorderWidth),
tangent2End: CGPoint(x: width - halfBorderWidth, y: halfBorderWidth),
radius: radius) // 左上角
context.addArc(tangent1End: CGPoint(x: width - halfBorderWidth, y: halfBorderWidth),
tangent2End: CGPoint(x: width - halfBorderWidth, y: radius + halfBorderWidth),
radius: radius) // 右上角
context.drawPath(using: .fillStroke)
let output = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return output
return output ?? UIImage()
}
}

extension UIImageView {
/*
/**
/ !!!只有当 imageView 不为nil 时,调用此方法才有效果

Expand All @@ -91,23 +101,35 @@ extension UIImageView {
// self.image = self.image?.imageAddCornerWithRadius(radius, andSize: self.bounds.size)
self.image = self.image?.kt_drawRectWithRoundedCorner(radius: radius, self.bounds.size)
}
*/

// Note: In Swift 4: Declarations in extensions cannot override. So I rename the function
func kt_imageViewAddCorner(radius: CGFloat) {
// 被注释的是图片添加圆角的 OC 写法
// self.image = self.image?.imageAddCornerWithRadius(radius, andSize: self.bounds.size)
self.image = self.image?.kt_drawRectWithRoundedCorner(radius: radius, self.bounds.size)
}
}

extension UIImage {
func kt_drawRectWithRoundedCorner(radius radius: CGFloat, _ sizetoFit: CGSize) -> UIImage {
func kt_drawRectWithRoundedCorner(radius: CGFloat, _ sizetoFit: CGSize) -> UIImage {
let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: sizetoFit)

UIGraphicsBeginImageContextWithOptions(rect.size, false, UIScreen.mainScreen().scale)
CGContextAddPath(UIGraphicsGetCurrentContext(),
UIBezierPath(roundedRect: rect, byRoundingCorners: UIRectCorner.AllCorners,
cornerRadii: CGSize(width: radius, height: radius)).CGPath)
CGContextClip(UIGraphicsGetCurrentContext())
UIGraphicsBeginImageContextWithOptions(rect.size, false, UIScreen.main.scale)
guard let context = UIGraphicsGetCurrentContext() else {
UIGraphicsEndImageContext()
return UIImage()
}
context.addPath(UIBezierPath(roundedRect: rect, byRoundingCorners: .allCorners,
cornerRadii: CGSize(width: radius, height: radius)).cgPath)
context.clip()

self.drawInRect(rect)
CGContextDrawPath(UIGraphicsGetCurrentContext(), .FillStroke)
self.draw(in: rect)
context.drawPath(using: .fillStroke)
let output = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

return output
return output ?? UIImage()
}
}

26 changes: 15 additions & 11 deletions CornerRadius/CornerRadius/ViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,39 +9,43 @@
import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let table = UITableView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height))

let identifier = "tableviewcell"

let table = UITableView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height))

override func viewDidLoad() {
super.viewDidLoad()

table.delegate = self
table.dataSource = self
table.register(CustomTableViewCell.self, forCellReuseIdentifier: identifier)

view.addSubview(table)
// 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.
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let identifier = "tableviewcell"
table.registerClass(CustomTableViewCell.self, forCellReuseIdentifier: identifier)
let cell = table.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath) as? CustomTableViewCell

cell?.selectionStyle = .None

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) as? CustomTableViewCell
cell?.selectionStyle = .none
cell?.setupContent(imgName: "photo")

return cell!
}

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 40
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 100
}
}