iOS开发中实现显示gif图片的方法(ios开发中实现显示gif图片的方法有哪些)
25-01-26
23
对于iOS开发中实现显示gif图片的方法感兴趣的读者,本文将会是一篇不错的选择,我们将详细介绍ios开发中实现显示gif图片的方法有哪些,并为您提供关于android--------GifView显示
对于iOS开发中实现显示gif图片的方法 感兴趣的读者,本文将会是一篇不错的选择,我们将详细介绍ios开发中实现显示gif图片的方法有哪些 ,并为您提供关于android -------- GifView 显示gif图片、android – 用库显示Gif图像、Android 显示GIF图片实例详解、android显示GIF图片 的有用信息。
本文目录一览:
iOS开发中实现显示gif图片的方法(ios开发中实现显示gif图片的方法有哪些) 我们知道Gif是由一阵阵画面组成的,而且每一帧画面播放的时常可能会不相等,观察上面两个例子,发现他们都没有对Gif中每一帧的显示时常做处理,这样的结果就是整个Gif中每一帧画面都是以固定的速度向前播放,很显然这并不总会符合需求。
于是自己写一个解析Gif的工具类,解决每一帧画面并遵循每一帧所对应的显示时间进行播放。
程序的思路如下:
1、首先使用ImageIO库中的CGImageSource家在Gif文件。
2、通过CGImageSource获取到Gif文件中的总的帧数,以及每一帧的显示时间。
3、通过CAKeyframeAnimation来完成Gif动画的播放。
下面直接上我写的解析和播放Gif的工具类的代码:
//
// SvGifView.h
// SvGifSample
//
// Created by maple on 3/28/13.
// copyright (c) 2013 smileEvday. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface SvGifView : UIView
/*
* @brief desingated initializer
*/
- (id)initWithCenter:(CGPoint)center fileURL:(NSURL*)fileURL;
/*
* @brief start Gif Animation
*/
- (void)startGif;
/*
* @brief stop Gif Animation
*/
- (void)stopGif;
/*
* @brief get frames image(CGImageRef) in Gif
*/
+ (NSArray*)framesInGif:(NSURL*)fileURL;
@end
//
// SvGifView.m
// SvGifSample
//
// Created by maple on 3/28/13.
// copyright (c) 2013 smileEvday. All rights reserved.
//
#import "SvGifView.h"
#import <ImageIO/ImageIO.h>
#import <QuartzCore/CoreAnimation.h>
/*
* @brief resolving gif information
*/
void getFrameInfo(CFURLRef url,NSMutableArray *frames,NSMutableArray *delayTimes,CGFloat *totalTime,CGFloat *gifWidth,CGFloat *gifheight)
{
CGImageSourceRef gifSource = CGImageSourceCreateWithURL(url,NULL);
// get frame count
size_t frameCount = CGImageSourceGetCount(gifSource);
for (size_t i = 0; i < frameCount; ++i) {
// get each frame
CGImageRef frame = CGImageSourceCreateImageAtIndex(gifSource,i,NULL);
[frames addobject:(id)frame];
CGImageRelease(frame);
// get gif info with each frame
NSDictionary *dict = (NSDictionary*)CGImageSourcecopyPropertiesAtIndex(gifSource,NULL);
NSLog(@"kCGImagePropertyGIFDictionary %@",[dict valueForKey:(Nsstring*)kCGImagePropertyGIFDictionary]);
// get gif size
if (gifWidth != NULL && gifheight != NULL) {
*gifWidth = [[dict valueForKey:(Nsstring*)kCGImagePropertyPixelWidth] floatValue];
*gifheight = [[dict valueForKey:(Nsstring*)kCGImagePropertyPixelHeight] floatValue];
}
// kCGImagePropertyGIFDictionary中kCGImagePropertyGIFDelayTime,kCGImagePropertyGIFUnclampedDelayTime值是一样的
NSDictionary *gifDict = [dict valueForKey:(Nsstring*)kCGImagePropertyGIFDictionary];
[delayTimes addobject:[gifDict valueForKey:(Nsstring*)kCGImagePropertyGIFDelayTime]];
if (totalTime) {
*totalTime = *totalTime + [[gifDict valueForKey:(Nsstring*)kCGImagePropertyGIFDelayTime] floatValue];
}
}
}
@interface SvGifView() {
NSMutableArray *_frames;
NSMutableArray *_frameDelayTimes;
CGFloat _totalTime; // seconds
CGFloat _width;
CGFloat _height;
}
@end
@implementation SvGifView
- (id)initWithCenter:(CGPoint)center fileURL:(NSURL*)fileURL;
{
self = [super initWithFrame:CGRectZero];
if (self) {
_frames = [[NSMutableArray alloc] init];
_frameDelayTimes = [[NSMutableArray alloc] init];
_width = 0;
_height = 0;
if (fileURL) {
getFrameInfo((CFURLRef)fileURL,_frames,_frameDelayTimes,&_totalTime,&_width,&_height);
}
self.frame = CGRectMake(0,_width,_height);
self.center = center;
}
return self;
}
+ (NSArray*)framesInGif:(NSURL *)fileURL
{
NSMutableArray *frames = [NSMutableArray arrayWithCapacity:3];
NSMutableArray *delays = [NSMutableArray arrayWithCapacity:3];
getFrameInfo((CFURLRef)fileURL,frames,delays,NULL,NULL);
return frames;
}
- (void)startGif
{
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"contents"];
NSMutableArray *times = [NSMutableArray arrayWithCapacity:3];
CGFloat currentTime = 0;
int count = _frameDelayTimes.count;
for (int i = 0; i < count; ++i) {
[times addobject:[NSNumber numberWithFloat:(currentTime / _totalTime)]];
currentTime += [[_frameDelayTimes objectAtIndex:i] floatValue];
}
[animation setKeyTimes:times];
NSMutableArray *images = [NSMutableArray arrayWithCapacity:3];
for (int i = 0; i < count; ++i) {
[images addobject:[_frames objectAtIndex:i]];
}
[animation setValues:images];
[animation setTimingFunction:[camediatimingFunction functionWithName:kcamediatimingFunctionLinear]];
animation.duration = _totalTime;
animation.delegate = self;
animation.repeatCount = 5;
[self.layer addAnimation:animation forKey:@"gifAnimation"];
}
- (void)stopGif
{
[self.layer removeAllAnimations];
}
// remove contents when animation end
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
self.layer.contents = nil;
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
}
@end
代码很短也比较容易,就不一一解释了。最开始的那个C函数主要就是用来解析Gif的,之所以用C函数是因为我要返回多个信息,而Objective-c只能返回一个参数,而且Objective-c和C语言可以很方便的混合编程。
另外再介绍两种使用UIImageView的方法:
1. 使用UIWebView播放
// 设定位置和大小
CGRect frame = CGRectMake(50,50,0);
frame.size = [UIImage imageNamed:@"guzhang.gif"].size;
// 读取gif图片数据
NSData *gif = [NSData dataWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"guzhang" ofType:@"gif"]];
// view生成
UIWebView *webView = [[UIWebView alloc] initWithFrame:frame];
webView.userInteractionEnabled = NO;//用户不可交互
[webView loadData:gif MIMEType:@"image/gif" textEncodingName:nil baseURL:nil];
[self.view addSubview:webView];
[webView release];
2.将gif图片分解成多张png图片,使用UIImageView播放。
代码如下:
UIImageView *gifImageView = [[UIImageView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
NSArray *gifArray = [NSArray arrayWithObjects:[UIImage imageNamed:@"1"],
[UIImage imageNamed:@"2"],
[UIImage imageNamed:@"3"],
[UIImage imageNamed:@"4"],
[UIImage imageNamed:@"5"],
[UIImage imageNamed:@"6"],
[UIImage imageNamed:@"7"],
[UIImage imageNamed:@"8"],
[UIImage imageNamed:@"9"],
[UIImage imageNamed:@"10"],
[UIImage imageNamed:@"11"],
[UIImage imageNamed:@"12"],
[UIImage imageNamed:@"13"],
[UIImage imageNamed:@"14"],
[UIImage imageNamed:@"15"],
[UIImage imageNamed:@"16"],
[UIImage imageNamed:@"17"],
[UIImage imageNamed:@"18"],
[UIImage imageNamed:@"19"],
[UIImage imageNamed:@"20"],
[UIImage imageNamed:@"21"],
[UIImage imageNamed:@"22"],nil];
gifImageView.animationImages = gifArray; //动画图片数组
gifImageView.animationDuration = 5; //执行一次完整动画所需的时长
gifImageView.animationRepeatCount = 1; //动画重复次数
[gifImageView startAnimating];
[self.view addSubview:gifImageView];
[gifImageView release];
注意:这个方法,如果gif动画每桢间的时间间隔不同,不能达到此效果。
您可能感兴趣的文章: 浅析IOS中播放gif动态图的方法 iOS Gif图片展示N种方式(原生+第三方) iOS之加载Gif图片的方法
android -------- GifView 显示gif图片 最近的项目需要在界面显示Gif动图,查找网络资料,总结了一下,分享一下,
一个GifView的gif图加载库以有效地显示GIF,
您可以启动,暂停和停止gifView
在app 的 build.gradle 中
implementation ''com.github.Cutta:GifView:1.4''
效果图:
1:布局直接显示
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<com.cunoraz.gifview.library.GifView
android:id="@+id/gif1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
custom:gif="@mipmap/gif1" />
<com.cunoraz.gifview.library.GifView
android:id="@+id/gif3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="15dp"
/>
</LinearLayout>
2:代码
/***
* 属性
*
* gifView1.setGifResource(R.mipmap.gif_start_stop);
* gifView1.play();
* gifView1.pause();
* gifView1.setGifResource(R.mipmap.gif5);
* gifView1.getGifResource();
* gifView1.setMovieTime(time);
* gifView1.getMovie();
*/
private void show(){
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (gifView1.isPlaying())
gifView1.pause();
}
});
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (gifView1.isPaused())
gifView1.play();
}
});
}
代码文档:https://github.com/Cutta/GifView
android – 用库显示Gif图像
我正在使用此库来显示gif图像:
https://github.com/felipecsl/GifImageView
但我不知道如何在这些代码中实现我的gif图像.我在资产文件夹中有一些GifImages.
这是我的代码:
PlayActivity.java:
import android.app.Activity;
import android.os.Bundle;
import com.felipecsl.gifimageview.library.GifImageView;
import java.io.IOException;
import java.io.InputStream;
public class PlayActivity extends Activity{
GifImageView gifView;
//byte[] bytes;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_play_activity);
try {
InputStream is = getAssets().open("rain_4.gif");
byte[] bytes = new byte[is.available()];
is.read(bytes);
is.close();
gifView = (GifImageView) findViewById(R.id.gifImageView);
gifView = new GifImageView(this);
gifView.setBytes(bytes);
gifView.startAnimation();
} catch (IOException e) {
e.printstacktrace();
}
}
@Override
protected void onStart() {
super.onStart();
if(gifView != null) gifView.startAnimation();
}
@Override
protected void onStop() {
super.onStop();
if(gifView != null) gifView.startAnimation();
}
}
和layout_play_activity.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".PlayActivity">
<com.felipecsl.gifimageview.library.GifImageView
android:id="@+id/gifImageView"
android:layout_gravity="center"
android:scaleType="fitCenter"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
解决方法
您提供的图书馆链接中有一个示例.加载GifImageView的方式与示例中的方式不同.样本从互联网上下载了一个gif.
以下是样本的MainActivity的片段:
GifImageView gifImageView = (GifImageView) findViewById(R.id.gifImageView);
new GifDataDownloader() {
@Override
protected void onPostExecute(final byte[] bytes) {
gifImageView.setBytes(bytes);
gifImageView.startAnimation();
Log.d(TAG,"GIF width is " + gifImageView.getGifWidth());
Log.d(TAG,"GIF height is " + gifImageView.getGifheight());
}
}.execute("http://gifs.joelglovier.com/aha/aha.gif");
解:
我不确定您是否可以使用此库从资产加载GifImageView,但我更喜欢使用离子库.这真的很好很简单.使用该库,您还可以根据需要拉伸gif图像:
https://github.com/koush/ion
简单示例:
ImageView imageView = (ImageView) findViewById(R.id.imageView);
Ion.with(imageView).load("http://gifs.joelglovier.com/aha/aha.gif");
Android 显示GIF图片实例详解 Android 显示gif图片实例详解
gif图动画在Android中还是比较常用的,比如像新浪微博中,有很多gif图片,而且展示非常好,所以我也想弄一个。经过我多方的搜索资料和整理,终于弄出来了,其实github上有很多开源的gif的展示代码,我下载过几个,但是都不是很理想,不是我完全想要的。所以有时候就得自己学会总结,把开源的东西整理成自己的,现在无聊,也正好有朋友需要,所以现在整理了一下,留着以后备用!
废话不多说,直接上图:
在这里主要用的是:android中的android.graphics.Movie 这个类,这是android提供给我们的一个非常方便的工具。
首先,重写控件View,自定义一个展示gif图的GifView,代码如下:
package net.loonggg.gif.view;
import net.loonggg.gif.R;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Movie;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
public class GifView extends View {
/**
* 默认为1秒
*/
private static final int DEFAULT_MOVIE_DURATION = 1000;
private int mMovieResourceId;
private Movie mMovie;
private long mMovieStart;
private int mCurrentAnimationTime = 0;
private float mLeft;
private float mTop;
private float mScale;
private int mMeasuredMovieWidth;
private int mMeasuredMovieHeight;
private boolean mVisible = true;
private volatile boolean mPaused = false;
public GifView(Context context) {
this(context,null);
}
public GifView(Context context,AttributeSet attrs) {
this(context,attrs,R.styleable.CustomTheme_gifViewStyle);
}
public GifView(Context context,AttributeSet attrs,int defStyle) {
super(context,defStyle);
setViewAttributes(context,defStyle);
}
@SuppressLint("NewApi")
private void setViewAttributes(Context context,int defStyle) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
setLayerType(View.LAYER_TYPE_SOFTWARE,null);
}
// 从描述文件中读出gif的值,创建出Movie实例
final TypedArray array = context.obtainStyledAttributes(attrs,R.styleable.GifView,defStyle,R.style.Widget_GifView);
mMovieResourceId = array.getResourceId(R.styleable.GifView_gif,-1);
mPaused = array.getBoolean(R.styleable.GifView_paused,false);
array.recycle();
if (mMovieResourceId != -1) {
mMovie = Movie.decodeStream(getResources().openRawResource(
mMovieResourceId));
}
}
/**
* 设置gif图资源
*
* @param movieResId
*/
public void setMovieResource(int movieResId) {
this.mMovieResourceId = movieResId;
mMovie = Movie.decodeStream(getResources().openRawResource(
mMovieResourceId));
requestLayout();
}
public void setMovie(Movie movie) {
this.mMovie = movie;
requestLayout();
}
public Movie getMovie() {
return mMovie;
}
public void setMovieTime(int time) {
mCurrentAnimationTime = time;
invalidate();
}
/**
* 设置暂停
*
* @param paused
*/
public void setPaused(boolean paused) {
this.mPaused = paused;
if (!paused) {
mMovieStart = android.os.SystemClock.uptimeMillis()
- mCurrentAnimationTime;
}
invalidate();
}
/**
* 判断gif图是否停止了
*
* @return
*/
public boolean isPaused() {
return this.mPaused;
}
@Override
protected void onMeasure(int widthMeasureSpec,int heightMeasureSpec) {
if (mMovie != null) {
int movieWidth = mMovie.width();
int movieHeight = mMovie.height();
int maximumWidth = MeasureSpec.getSize(widthMeasureSpec);
float scaleW = (float) movieWidth / (float) maximumWidth;
mScale = 1f / scaleW;
mMeasuredMovieWidth = maximumWidth;
mMeasuredMovieHeight = (int) (movieHeight * mScale);
setMeasuredDimension(mMeasuredMovieWidth,mMeasuredMovieHeight);
} else {
setMeasuredDimension(getSuggestedMinimumWidth(),getSuggestedMinimumHeight());
}
}
@Override
protected void onLayout(boolean changed,int l,int t,int r,int b) {
super.onLayout(changed,l,t,r,b);
mLeft = (getWidth() - mMeasuredMovieWidth) / 2f;
mTop = (getHeight() - mMeasuredMovieHeight) / 2f;
mVisible = getVisibility() == View.VISIBLE;
}
@Override
protected void onDraw(Canvas canvas) {
if (mMovie != null) {
if (!mPaused) {
updateAnimationTime();
drawMovieFrame(canvas);
invalidateView();
} else {
drawMovieFrame(canvas);
}
}
}
@SuppressLint("NewApi")
private void invalidateView() {
if (mVisible) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
postInvalidateOnAnimation();
} else {
invalidate();
}
}
}
private void updateAnimationTime() {
long Now = android.os.SystemClock.uptimeMillis();
// 如果第一帧,记录起始时间
if (mMovieStart == 0) {
mMovieStart = Now;
}
// 取出动画的时长
int dur = mMovie.duration();
if (dur == 0) {
dur = DEFAULT_MOVIE_DURATION;
}
// 算出需要显示第几帧
mCurrentAnimationTime = (int) ((Now - mMovieStart) % dur);
}
private void drawMovieFrame(Canvas canvas) {
// 设置要显示的帧,绘制即可
mMovie.setTime(mCurrentAnimationTime);
canvas.save(Canvas.MATRIX_SAVE_FLAG);
canvas.scale(mScale,mScale);
mMovie.draw(canvas,mLeft / mScale,mTop / mScale);
canvas.restore();
}
@SuppressLint("NewApi")
@Override
public void onScreenStateChanged(int screenState) {
super.onScreenStateChanged(screenState);
mVisible = screenState == SCREEN_STATE_ON;
invalidateView();
}
@SuppressLint("NewApi")
@Override
protected void onVisibilityChanged(View changedView,int visibility) {
super.onVisibilityChanged(changedView,visibility);
mVisible = visibility == View.VISIBLE;
invalidateView();
}
@Override
protected void onWindowVisibilityChanged(int visibility) {
super.onWindowVisibilityChanged(visibility);
mVisible = visibility == View.VISIBLE;
invalidateView();
}
}
Movie其实管理着GIF动画中的多个帧,只需要通过 setTime() 一下就可以让它在draw()的时候绘出相应的那帧图像。通过当前时间与duration之间的换算关系,是很容易实现GIF动起来的效果。
其次,在xml布局文件中,把这个view定义进去,代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<net.loonggg.gif.view.GifView
android:id="@+id/gif1"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center_horizontal"
android:enabled="false" />
<net.loonggg.gif.view.GifView
android:id="@+id/gif2"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_gravity="center_horizontal"
android:enabled="false" />
</LinearLayout>
最后,在MainActivity中的使用,代码如下:
package net.loonggg.gif;
import net.loonggg.gif.view.GifView;
import android.app.Activity;
import android.os.Bundle;
public class Gif extends Activity {
private GifView gif1,gif2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gif1 = (GifView) findViewById(R.id.gif1);
// 设置背景gif图片资源
gif1.setMovieResource(R.raw.kitty);
gif2 = (GifView) findViewById(R.id.gif2);
gif2.setMovieResource(R.raw.b);
// 设置暂停
// gif2.setPaused(true);
}
}
注意:与ImageView和其他View唯一的区别在于我加了一个gif属性。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="GifView">
<attr name="gif" format="reference" />
<attr name="paused" format="boolean" />
</declare-styleable>
<declare-styleable name="CustomTheme">
<attr name="gifViewStyle" format="reference" />
</declare-styleable>
</resources>
这个代码已经非常好了,使用也非常方便,其实不懂代码是什么意思也可以很好的用,只需要懂得我写注释的那几行和Activity里面的那几行代码就可以了!
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
android显示GIF图片 通过开源项目GifView
主页:http://code.google.com/p/gifview/
下载:http://code.google.com/p/gifview/downloads/list
简介:android中现在没有直接显示gif的view,只能通过mediaplay来显示,且还常常不能正常显示出来,为此写了这个gifview,其用法和imageview一样,支持gif图片
使用方法:
1-把GifView.jar加入你的项目。
2-在xml中配置GifView的基本属性,GifView继承自View类,和Button、ImageView一样是一个UI控件。如:
<com.ant.liao.GifView android:id="@+id/gif2"
android:layout_height="wrap_content" android:layout_width="wrap_content"
android:paddingTop="4px" android:paddingLeft="14px" android:enabled="false" />
3-在代码中配置常用属性:
// 从xml中得到GifView的句柄
gf1 = (GifView) findViewById(R.id.gif1);
// 设置Gif图片源
gf1.setGifImage(R.drawable.gif1);
// 添加监听器
gf1.setOnClickListener(this);
// 设置显示的大小,拉伸或者压缩
gf1.setShowDimension(300, 300);
// 设置加载方式:先加载后显示、边加载边显示、只显示第一帧再显示
gf1.setGifImageType(GifImageType.COVER);
GifView的Jar包共有四个类
:
GifAction.java 观察者类,监视GIF是否加载成功
GifFrame.java 里面三个成员:当前图片、延时、下张Frame的链接。
GifDecoder.java 解码线程类
GifView.java 主类,包括常用方法,如GifView构造方法、设置图片源、延迟、绘制等。
亲测可以用。
原文:http://www.eoeandroid.com/thread-184872-1-1.html
今天的关于iOS开发中实现显示gif图片的方法 和ios开发中实现显示gif图片的方法有哪些 的分享已经结束,谢谢您的关注,如果想了解更多关于android -------- GifView 显示gif图片、android – 用库显示Gif图像、Android 显示GIF图片实例详解、android显示GIF图片 的相关知识,请在本站进行查询。