Skip to content

Commit

Permalink
Add fontMinimumScaleFactor
Browse files Browse the repository at this point in the history
  • Loading branch information
SD10 committed Sep 22, 2017
1 parent 337dc3c commit 05c42b9
Show file tree
Hide file tree
Showing 2 changed files with 102 additions and 57 deletions.
128 changes: 87 additions & 41 deletions Sources/AvatarView.swift
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
/*
MIT License

Copyright (c) 2017 MessageKit

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
Expand All @@ -25,53 +25,85 @@
import Foundation

open class AvatarView: UIView {

// MARK: - Properties

public var adjustsFontSizeToFitWidth = true

open var avatar: Avatar = Avatar()

open var imageView = UIImageView()

public var image: UIImage? {
return imageView.image
}

open var placeholderFont: UIFont = UIFont.preferredFont(forTextStyle: .caption1) {
didSet {
set(avatar: avatar)
}
}

open var placeholderTextColor: UIColor = .white {
didSet {
set(avatar: avatar)
}
}

open var fontMinimumScaleFactor: CGFloat = 0.5

open var adjustsFontSizeToFitWidth = true

private var minimumFontSize: CGFloat {
return placeholderFont.pointSize * fontMinimumScaleFactor
}

private var radius: CGFloat?
// MARK: - Overrided Properties

// MARK: - Overridden Properties
open override var frame: CGRect {
didSet {
imageView.frame = bounds
setCorner(radius: self.radius)
}
}


open override var bounds: CGRect {
didSet {
imageView.frame = bounds
setCorner(radius: self.radius)
}
}

// MARK: - Initializers
override public init(frame: CGRect) {
super.init(frame: frame)
prepareView()
}

convenience public init() {
self.init(frame: .zero)
}
private func getImageFrom(initals: String, withColor color: UIColor = UIColor.white, fontSize: CGFloat = 14) -> UIImage {

private func getImageFrom(initals: String) -> UIImage {
let width = frame.width
let height = frame.height
if width == 0 || height == 0 {return UIImage()}
var font = UIFont.systemFont(ofSize: fontSize)
var font = placeholderFont

_ = UIGraphicsBeginImageContext(CGSize(width: width, height: height))
let context = UIGraphicsGetCurrentContext()!

//// Text Drawing
let textRect = calculateTextRect(outerViewWidth: width, outerViewHeight: height)
if adjustsFontSizeToFitWidth,
initals.width(considering: textRect.height, and: font) > textRect.width {
let newFontSize = calculateFontSize(text: initals, font: font, width: textRect.width, height: textRect.height)
font = UIFont.systemFont(ofSize: newFontSize)
font = placeholderFont.withSize(newFontSize)
}

let textStyle = NSMutableParagraphStyle()
textStyle.alignment = .center
let textFontAttributes = [NSFontAttributeName: font, NSForegroundColorAttributeName: color, NSParagraphStyleAttributeName: textStyle]
let textFontAttributes: [String: Any] = [NSFontAttributeName: font, NSForegroundColorAttributeName: placeholderTextColor, NSParagraphStyleAttributeName: textStyle]

let textTextHeight: CGFloat = initals.boundingRect(with: CGSize(width: textRect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: textFontAttributes, context: nil).height
context.saveGState()
context.clip(to: textRect)
Expand All @@ -80,21 +112,25 @@ open class AvatarView: UIView {
guard let renderedImage = UIGraphicsGetImageFromCurrentImageContext() else { assertionFailure("Could not create image from context"); return UIImage()}
return renderedImage
}

/**
Recursively found the biggest size that can fit to given width and height
Recursively find the biggest size to fit the text with a given width and height
*/
private func calculateFontSize(text: String, font: UIFont, width: CGFloat, height: CGFloat) -> CGFloat {
if text.width(considering: height, and: font) > width {
let newFont = UIFont.systemFont(ofSize: (font.pointSize - 1))
return calculateFontSize(text: text, font: newFont, width: width, height: height)
let newFont = font.withSize(font.pointSize - 1)
if newFont.pointSize > minimumFontSize {
return font.pointSize
} else {
return calculateFontSize(text: text, font: newFont, width: width, height: height)
}
}
return font.pointSize
}

/**
Calculates the inner circle's width.
Assumption: Corner radius cannot be more than width/2 (this creates circle)
Note: Assumes corner radius cannot be more than width/2 (this creates circle).
*/
private func calculateTextRect(outerViewWidth: CGFloat, outerViewHeight: CGFloat) -> CGRect {
guard outerViewWidth > 0 else {
Expand All @@ -111,15 +147,15 @@ open class AvatarView: UIView {
// In case the font exactly fits to the region, put 2 pixel both left and right
return CGRect(x: startX+2, y: startY, width: w-4, height: h)
}

required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

// MARK: - Internal methods

internal func prepareView() {
setBackground(color: UIColor.gray)
backgroundColor = .gray
contentMode = .scaleAspectFill
layer.masksToBounds = true
clipsToBounds = true
Expand All @@ -129,17 +165,13 @@ open class AvatarView: UIView {
imageView.image = avatar.image ?? getImageFrom(initals: avatar.initals)
setCorner(radius: nil)
}

// MARK: - Open setters

open func set(avatar: Avatar) {
imageView.image = avatar.image ?? getImageFrom(initals: avatar.initals)
}

open func setBackground(color: UIColor) {
backgroundColor = color
}


open func setCorner(radius: CGFloat?) {
guard let radius = radius else {
//if corner radius not set default to Circle
Expand All @@ -150,10 +182,24 @@ open class AvatarView: UIView {
self.radius = radius
layer.cornerRadius = radius
}

// MARK: - Open getters

open func getImage() -> UIImage? {

}

extension FloatingPoint {
var degreesToRadians: Self { return self * .pi / 180 }
var radiansToDegrees: Self { return self * 180 / .pi }
}

public extension AvatarView {

@available(*, deprecated: 0.8.0, message: "setBackground(_:) has been deprecated. Please use the backgroundColor property instead.")
public func setBackground(color: UIColor) {
backgroundColor = color
}

@available(*, deprecated: 0.8.0, message: "getImage() has been deprecated. Please use the image property instead.")
public func getImage() -> UIImage? {
return imageView.image
}

}
31 changes: 15 additions & 16 deletions Tests/AvatarViewTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,57 +26,56 @@ import XCTest
@testable import MessageKit

class AvatarViewTests: XCTestCase {


var avatarView: AvatarView!

override func setUp() {
super.setUp()
avatarView = AvatarView()
avatarView.frame.size = CGSize(width: 30, height: 30)
}

override func tearDown() {
super.tearDown()
avatarView = nil
}

func testNoParams() {
let avatarView = AvatarView()
XCTAssertEqual(avatarView.avatar.initals, "?")
XCTAssertEqual(avatarView.layer.cornerRadius, 15.0)
XCTAssertEqual(avatarView.backgroundColor, UIColor.gray)
}

func testWithImage() {
let avatarView = AvatarView()
let avatar = Avatar(image: UIImage())
avatarView.set(avatar: avatar)
XCTAssertEqual(avatar.initals, "?")
XCTAssertEqual(avatarView.layer.cornerRadius, 15.0)
XCTAssertEqual(avatarView.backgroundColor, UIColor.gray)
}

func testInitalsOnly() {
let avatarView = AvatarView()
let avatar = Avatar(initals: "DL")
avatarView.set(avatar: avatar)
XCTAssertEqual(avatar.initals, "DL")
XCTAssertEqual(avatarView.layer.cornerRadius, 15.0)
XCTAssertEqual(avatarView.backgroundColor, UIColor.gray)
}

func testSetBackground() {
let avatarView = AvatarView()
XCTAssertEqual(avatarView.backgroundColor, UIColor.gray)
avatarView.setBackground(color: UIColor.red)
avatarView.backgroundColor = UIColor.red
XCTAssertEqual(avatarView.backgroundColor, UIColor.red)
}

func testGetImage() {
let image = UIImage()
let avatar = Avatar(image: image)
let avatarView = AvatarView()
avatarView.set(avatar: avatar)
XCTAssertEqual(avatarView.getImage(), image)
XCTAssertEqual(avatarView.image, image)
}

func testRoundedCorners() {
let avatarView = AvatarView()
let avatar = Avatar(image: UIImage())
avatarView.set(avatar: avatar)
XCTAssertEqual(avatarView.layer.cornerRadius, 15.0)
Expand Down

0 comments on commit 05c42b9

Please sign in to comment.