
StringをUIImageに変換して動的にCALayerを生成する
説明
StringをUIImageに変換して、そのUIImageをCALayerをに描画して、CALayerを画面に描画してます。諸事情により下記のような動きにしてます。
実行
ソース
実装
//
// ViewController.swift
// Dynamically generate uiimage
//
// Created by ryosuke-hujisawa on 2017/10/22.
// Copyright © 2017年 ryosuke-hujisawa. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITextViewDelegate {
@IBOutlet weak var textView: UITextView!
//追加された画像を挿入削除する配列
var logoImages: [CALayer] = []
//画像の位置を定めるための変数
var tapCount:Int = 0
//arrayを取り出したり挿入したりする配列に使う変数
var tapCountArray:Int = 0
//可変変数を使うための辞書型
var dic: Dictionary<String, Any> = [:]
//可変変数を取り出すための変数
let varName = ""
//uiimageを定義する
var image1:UIImage?
override func viewDidLoad() {
super.viewDidLoad()
textView.delegate = self
}
/*
テキストビューがリターンされたらキーボードを閉じる
*/
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if (text == "\n") {
textView.resignFirstResponder()
return false
}
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
画像を追加する関数
*/
@IBAction func add(_ sender: Any) {
/*
StringをUIImageにする
*/
let text = textView.text
let font = UIFont.boldSystemFont(ofSize: 120)
UIGraphicsBeginImageContext(CGSize(width: 300, height: 300))
let textRect = CGRect(x:0, y:0, width:250, height:120)
let textStyle = NSMutableParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
let textFontAttributes = [
NSAttributedStringKey.font: font,
NSAttributedStringKey.foregroundColor: UIColor.yellow,
NSAttributedStringKey.paragraphStyle: textStyle
]
text?.draw(in: textRect, withAttributes: textFontAttributes)
let newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext()
image1 = newImage
/*
CALayerを動的に増やす
*/
//80pt感覚で画像を配置する
self.tapCount += 80
//辞書型から取り出すためにユニークな名前を画像につける
dic[varName] = tapCount
//ユニークな番号に画像を挿入する
self.tapCountArray += 1
dic[varName]! = CALayer()
let logoImage: UIImage = image1!
(dic[varName]! as! CALayer).contents = logoImage.cgImage
(dic[varName]! as! CALayer).frame = CGRect(x: tapCount, y: tapCount, width: 100, height: 100)
view.layer.addSublayer(dic[varName]! as! CALayer)
logoImages.append( dic[varName]! as! CALayer )
}
/*
CALayerの配列の最後尾から削除する
*/
@IBAction func deleteImage(_ sender: Any) {
self.tapCount -= 80
self.tapCountArray -= 1
print(tapCount)
print(tapCountArray)
logoImages[ logoImages.count - 1 ].removeFromSuperlayer()
logoImages.removeLast()
}
}