Iphone UIImageView에서 애니메이션 GIF 이미지 추가
UI 이미지 보기의 URL에서 애니메이션 Gif 이미지를 로드해야 합니다.
일반 코드를 사용했을 때 이미지가 로드되지 않았습니다.
애니메이션 Gif 이미지를 로드할 수 있는 다른 방법이 있습니까?
UIImageView* animatedImageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
animatedImageView.animationImages = [NSArray arrayWithObjects:
[UIImage imageNamed:@"image1.gif"],
[UIImage imageNamed:@"image2.gif"],
[UIImage imageNamed:@"image3.gif"],
[UIImage imageNamed:@"image4.gif"], nil];
animatedImageView.animationDuration = 1.0f;
animatedImageView.animationRepeatCount = 0;
[animatedImageView startAnimating];
[self.view addSubview: animatedImageView];
둘 이상의 gif 이미지를 로드할 수 있습니다.
다음 ImageMagick 명령을 사용하여 gif를 분할할 수 있습니다.
convert +adjoin loading.gif out%d.gif
승인된 답변을 찾았지만 최근 UIImage+애니메이션을 발견했습니다.GIF 이미지 확장입니다.다음 범주를 제공합니다.
+[UIImage animatedImageWithAnimatedGIFURL:(NSURL *)url]
다음을 간단히 수행할 수 있습니다.
#import "UIImage+animatedGIF.h"
UIImage* mygif = [UIImage animatedImageWithAnimatedGIFURL:[NSURL URLWithString:@"http://en.wikipedia.org/wiki/File:Rotating_earth_(large).gif"]];
마법처럼 작동합니다.
Gif Image를 사용하기 위한 최고의 솔루션이 여기 있습니다.프로젝트에 Github의 SD Web Image를 추가합니다.
#import "UIImage+GIF.h"
_imageViewAnimatedGif.image= [UIImage sd_animatedGIFNamed:@"thumbnail"];
타사 라이브러리를 사용하지 않으려면,
extension UIImageView {
func setGIFImage(name: String, repeatCount: Int = 0 ) {
DispatchQueue.global().async {
if let gif = UIImage.makeGIFFromCollection(name: name, repeatCount: repeatCount) {
DispatchQueue.main.async {
self.setImage(withGIF: gif)
self.startAnimating()
}
}
}
}
private func setImage(withGIF gif: GIF) {
animationImages = gif.images
animationDuration = gif.durationInSec
animationRepeatCount = gif.repeatCount
}
}
extension UIImage {
class func makeGIFFromCollection(name: String, repeatCount: Int = 0) -> GIF? {
guard let path = Bundle.main.path(forResource: name, ofType: "gif") else {
print("Cannot find a path from the file \"\(name)\"")
return nil
}
let url = URL(fileURLWithPath: path)
let data = try? Data(contentsOf: url)
guard let d = data else {
print("Cannot turn image named \"\(name)\" into data")
return nil
}
return makeGIFFromData(data: d, repeatCount: repeatCount)
}
class func makeGIFFromData(data: Data, repeatCount: Int = 0) -> GIF? {
guard let source = CGImageSourceCreateWithData(data as CFData, nil) else {
print("Source for the image does not exist")
return nil
}
let count = CGImageSourceGetCount(source)
var images = [UIImage]()
var duration = 0.0
for i in 0..<count {
if let cgImage = CGImageSourceCreateImageAtIndex(source, i, nil) {
let image = UIImage(cgImage: cgImage)
images.append(image)
let delaySeconds = UIImage.delayForImageAtIndex(Int(i),
source: source)
duration += delaySeconds
}
}
return GIF(images: images, durationInSec: duration, repeatCount: repeatCount)
}
class func delayForImageAtIndex(_ index: Int, source: CGImageSource!) -> Double {
var delay = 0.0
// Get dictionaries
let cfProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil)
let gifPropertiesPointer = UnsafeMutablePointer<UnsafeRawPointer?>.allocate(capacity: 0)
if CFDictionaryGetValueIfPresent(cfProperties, Unmanaged.passUnretained(kCGImagePropertyGIFDictionary).toOpaque(), gifPropertiesPointer) == false {
return delay
}
let gifProperties:CFDictionary = unsafeBitCast(gifPropertiesPointer.pointee, to: CFDictionary.self)
// Get delay time
var delayObject: AnyObject = unsafeBitCast(
CFDictionaryGetValue(gifProperties,
Unmanaged.passUnretained(kCGImagePropertyGIFUnclampedDelayTime).toOpaque()),
to: AnyObject.self)
if delayObject.doubleValue == 0 {
delayObject = unsafeBitCast(CFDictionaryGetValue(gifProperties,
Unmanaged.passUnretained(kCGImagePropertyGIFDelayTime).toOpaque()), to: AnyObject.self)
}
delay = delayObject as? Double ?? 0
return delay
}
}
class GIF: NSObject {
let images: [UIImage]
let durationInSec: TimeInterval
let repeatCount: Int
init(images: [UIImage], durationInSec: TimeInterval, repeatCount: Int = 0) {
self.images = images
self.durationInSec = durationInSec
self.repeatCount = repeatCount
}
}
사용할 항목,
override func viewDidLoad() {
super.viewDidLoad()
imageView.setGIFImage(name: "gif_file_name")
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
imageView.stopAnimating()
}
gif 파일은 .xcassets 폴더가 아닌 프로젝트에 추가해야 합니다.
이 링크 확인
다음 클래스를 가져옵니다.UIImage+애니메이션GIF.h, UI이미지+애니메이션 GIF.m
이 코드 사용
NSURL *urlZif = [[NSBundle mainBundle] URLForResource:@"dots64" withExtension:@"gif"];
NSString *path=[[NSBundle mainBundle]pathForResource:@"bar180" ofType:@"gif"];
NSURL *url=[[NSURL alloc] initFileURLWithPath:path];
imageVw.image= [UIImage animatedImageWithAnimatedGIFURL:url];
이것이 도움이 되기를 바랍니다.
이것은 UIImageView를 사용해야 하는 요구 사항을 충족하지 못하지만, 이를 통해 작업을 단순화할 수 있습니다.UI WebView 사용을 고려해 보셨습니까?
NSString *gifUrl = @"http://gifs.com";
NSURL *url = [NSURL URLWithString: gifUrl];
[webView loadRequest: [NSURLRequest requestWithURL:url]
인터넷이 필요한 URL에 링크하는 대신 HTML 파일을 Xcode 프로젝트로 가져와서 문자열에 루트를 설정할 수 있습니다.
여기 재미있는 도서관이 있습니다: https://github.com/Flipboard/FLAnimatedImage
데모 예제를 테스트해 봤는데 작동이 잘 됩니다.UIImageView의 하위 항목입니다.그래서 스토리보드에서도 직접 사용할 수 있다고 생각합니다.
건배.
이미 답변이 승인된 것은 알지만, iOS에 Gif 지원을 추가하는 내장 프레임워크를 만들었기 때문에 다른 UIKit Framework 클래스를 사용하는 것처럼 느껴집니다.
다음은 예입니다.
UIGifImage *gif = [[UIGifImage alloc] initWithData:imageData];
anUiImageView.image = gif;
https://github.com/ObjSal/UIGifImage/releases 에서 최신 릴리스를 다운로드합니다.
살
URL에서 gif 이미지를 로드해야 하는 경우 항상 gif를 이미지 태그에 포함시킬 수 있습니다.UIWebView
.
스위프트 3
스위프트 버전이 필요한 분들을 위한 업데이트입니다!
며칠 전에 저는 이런 일을 해야 했습니다.저는 특정 매개 변수에 따라 서버에서 일부 데이터를 로드하는 동안 "로딩"의 다른 gif 이미지를 보여주고 싶었습니다.나는 그것을 할 수 있는 옵션을 찾고 있었습니다.UIImageView
하지만 안타깝게도 .gif 이미지를 분할하지 않고는 할 수 있는 방법을 찾지 못했습니다.그래서 저는 다음을 사용하여 솔루션을 구현하기로 결정했습니다.UIWebView
그리고 나는 그것을 공유하고 싶습니다:
extension UIView{
func animateWithGIF(name: String){
let htmlString: String = "<!DOCTYPE html><html><head><title></title></head>" +
"<body style=\"background-color: transparent;\">" +
"<img src=\""+name+"\" align=\"middle\" style=\"width:100%;height:100%;\">" +
"</body>" +
"</html>"
let path: NSString = Bundle.main.bundlePath as NSString
let baseURL: URL = URL(fileURLWithPath: path as String) // to load images just specifying its name without full path
let frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)
let gifView = UIWebView(frame: frame)
gifView.isOpaque = false // The drawing system composites the view normally with other content.
gifView.backgroundColor = UIColor.clear
gifView.loadHTMLString(htmlString, baseURL: baseURL)
var s: [UIView] = self.subviews
for i in 0 ..< s.count {
if s[i].isKind(of: UIWebView.self) { s[i].removeFromSuperview() }
}
self.addSubview(gifView)
}
func animateWithGIF(url: String){
self.animateWithGIF(name: url)
}
}
나는 연장했습니다.UIView
이는 추가적으로UIWebView
하위 보기로 지정하고 이름을 전달하는 .gif 이미지를 표시합니다.
이제 내 안에서UIViewController
나는 있습니다.UIView
loadingView라는마다 loadingView라는 이름의 'loadingView'는 다음과했습니다. loadingView'와 'loadingView'는 .의 두 번째 지표입니다.
class ViewController: UIViewController {
@IBOutlet var loadingView: UIView!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
configureLoadingView(name: "loading.gif")
}
override func viewDidLoad() {
super.viewDidLoad()
// .... some code
// show "loading" image
showLoadingView()
}
func showLoadingView(){
loadingView.isHidden = false
}
func hideLoadingView(){
loadingView.isHidden = true
}
func configureLoadingView(name: String){
loadingView.animateWithGIF(name: "name")// change the image
}
}
단순히 함수라고 불리는 gif 이미지를 바꾸고 싶을 때configureLoadingView()
.gif 하는 .gif 이미지.showLoadingView()
,hideLoadingView()
제대로 모든 것이 잘 작동합니다!
그렇지만.....
했다면, 을 한 할 수 있습니다.UIImage
은 정적인 방법입니다.UIImage.animatedImageNamed
다음과 같이:
imageView.image = UIImage.animatedImageNamed("imageName", duration: 1.0)
문서에서:
이 메서드는 name 매개 변수에 제공된 기본 파일 이름에 일련의 숫자를 추가하여 일련의 파일을 로드합니다.애니메이션 이미지에 포함된 모든 이미지는 동일한 크기와 크기를 공유해야 합니다.
아니면 당신은 그것으로 만들 수 있습니다.UIImage.animatedImageWithImages
다음과 같은 방법:
let images: [UIImage] = [UIImage(named: "imageName1")!,
UIImage(named: "imageName2")!,
...,
UIImage(named: "imageNameN")!]
imageView.image = UIImage.animatedImage(with: images, duration: 1.0)
문서에서:
기존 이미지 집합에서 애니메이션 이미지를 만들고 반환합니다.애니메이션 이미지에 포함된 모든 이미지는 동일한 크기와 크기를 공유해야 합니다.
스위프트와 킹 피셔와 함께
lazy var animatedPart: AnimatedImageView = {
let img = AnimatedImageView()
if let src = Bundle.main.url(forResource: "xx", withExtension: "gif"){
img.kf.setImage(with: src)
}
return img
}()
https://github.com/Flipboard/FLAnimatedImage 를 사용할 수 있습니다.
#import "FLAnimatedImage.h"
NSData *dt=[NSData dataWithContentsOfFile:path];
imageView1 = [[FLAnimatedImageView alloc] init];
FLAnimatedImage *image1 = [FLAnimatedImage animatedImageWithGIFData:dt];
imageView1.animatedImage = image1;
imageView1.frame = CGRectMake(0, 5, 168, 80);
[self.view addSubview:imageView1];
스위프트 3:
위에서 제안한 대로 FLA Nimated Image View와 함께 FLA Nimated Image를 사용하고 있습니다.그리고 xcassets의 데이터 세트로 gif를 로드하고 있습니다.이를 통해 외관과 앱 슬라이싱 목적으로 아이폰과 ipad에 대해 서로 다른 gif를 제공할 수 있습니다.이것은 제가 시도한 다른 어떤 것보다 훨씬 더 성능이 좋습니다..stopAnimation()을 사용하여 일시 중지하기도 쉽습니다.
if let asset = NSDataAsset(name: "animation") {
let gifData = asset.data
let gif = FLAnimatedImage(animatedGIFData: gifData)
imageView.animatedImage = gif
}
언급URL : https://stackoverflow.com/questions/4386675/add-animated-gif-image-in-iphone-uiimageview
'sourcecode' 카테고리의 다른 글
파이썬에서 두 배의 정밀 부동값? (0) | 2023.08.26 |
---|---|
AJAX에서 device의 401 상태를 우아하게 처리하려면 어떻게 해야 합니까? (0) | 2023.08.26 |
도커를 통해 mariadb 연결이 실패하는 이유는 무엇입니까? (0) | 2023.08.26 |
비활성화되지 않은 경우에만 호버 및 활성화 (0) | 2023.08.26 |
Linux에서 입력 파일을 사용하여 여러 행을 업데이트하는 Mysql 쿼리 (0) | 2023.08.26 |