Last active
August 23, 2016 06:03
-
-
Save paulmars/89c51e901f36b72f6ef8e891de2ede77 to your computer and use it in GitHub Desktop.
animated gif or images
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// TypedImage.swift | |
// | |
// Created by Paul McKellar on 8/22/16. | |
// Copyright © 2016 Paul McKellar. All rights reserved. | |
// | |
import UIKit | |
import FLAnimatedImage | |
class TypedImageView: UIView { | |
var buffer: NSMutableData? | |
var imageView: UIImageView! | |
var animatedImageView: FLAnimatedImageView! | |
override init(frame: CGRect) { | |
super.init(frame: frame); | |
self.animatedImageView = FLAnimatedImageView() | |
self.animatedImageView.contentMode = .ScaleAspectFit | |
self.imageView = UIImageView() | |
self.imageView.contentMode = .ScaleAspectFit | |
let randomRed:CGFloat = CGFloat(drand48()) | |
let randomGreen:CGFloat = CGFloat(drand48()) | |
let randomBlue:CGFloat = CGFloat(drand48()) | |
let backgroundColor = UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: 1.0) | |
self.animatedImageView.backgroundColor = backgroundColor | |
self.imageView.backgroundColor = backgroundColor | |
self.backgroundColor = backgroundColor | |
return; | |
} | |
required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented"); } | |
func setImage(buffer: NSMutableData) -> Void { | |
self.animatedImageView.removeFromSuperview() | |
self.imageView.removeFromSuperview() | |
self.buffer = buffer | |
if (self.imageType(buffer) == "gif") { | |
self.animatedImageView.animatedImage = FLAnimatedImage(animatedGIFData: buffer) | |
self.animatedImageView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height) | |
self.addSubview(self.animatedImageView) | |
} | |
else { | |
self.imageView.image = UIImage(data: buffer) | |
self.imageView.frame = CGRectMake(0, 0, self.frame.width, self.frame.height) | |
self.addSubview(self.imageView) | |
} | |
} | |
func setSize(size: CGSize) -> Void { | |
self.imageView.frame.size = size | |
self.animatedImageView.frame.size = size | |
self.frame.size = size | |
} | |
func imageType(imgData : NSData) -> String | |
{ | |
var c = [UInt8](count: 1, repeatedValue: 0) | |
imgData.getBytes(&c, length: 1) | |
let ext : String | |
switch (c[0]) { | |
case 0xFF: | |
ext = "jpg" | |
case 0x89: | |
ext = "png" | |
case 0x47: | |
ext = "gif" | |
case 0x49, 0x4D : | |
ext = "tiff" | |
default: | |
ext = "" //unknown | |
} | |
return ext | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment