StringからUIImage – Swift3 , Xcode9

 

環境

  • String
  • UIImage
  • Swift3
  • Xcode9
  • siwft
  • xcode

実行

on.gif

説明

私情により動的に作ったり消したりしてます。この部分の実装に関してはこちらより。

実装

//
//  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: [UIImageView] = []
    //画像の位置を定めるための変数
    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


        /*


         UIImageを動的に増やす



         */

        //80pt感覚で画像を配置する
        self.tapCount += 80
        //辞書型から取り出すためにユニークな名前を画像につける
        dic[varName] = tapCount
        print("\(dic[varName]!)")
        //ユニークな番号に画像を挿入する
        //image1はテキストの画像
        dic[varName]! = UIImageView(image:image1)
        let rect:CGRect = CGRect(x:tapCount, y:tapCount, width:500, height:500)
        (dic[varName]! as! UIView).frame = rect
        //配列に画像を挿入する
        logoImages.append(   dic[varName]! as! UIImageView  )
        print( logoImages )
        //画像をviewに挿入する
        self.view.addSubview(logoImages[ tapCountArray ]  )
        print( logoImages[ tapCountArray ] )
        print(tapCountArray)
        //配列の番号を増やしていく
        self.tapCountArray += 1
        print(tapCountArray)
    }



     /*


     UIImageの配列の最後尾から削除する

     */
    @IBAction func deleteImage(_ sender: Any) {
        self.tapCount -= 80
        self.tapCountArray -= 1
        print(tapCount)
        print(tapCountArray)
        //配列の最後の値をviewから画像を削除する
        logoImages[ logoImages.count - 1 ].removeFromSuperview()
        //配列の最後の値を削除する
        logoImages.removeLast()
    }
}

ソース

GitHub

藤沢瞭介(Ryosuke Hujisawa)
  • りょすけと申します。18歳からプログラミングをはじめ、今はフロントエンドでReactを書いたり、AIの勉強を頑張っています。off.tokyoでは、ハイテクやガジェット、それからプログラミングに関する情報まで、エンジニアに役立つ情報を日々発信しています!

Swift