iOS GIF动态图(显示、上传、保存)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS GIF动态图(显示、上传、保存)相关的知识,希望对你有一定的参考价值。

参考技术A ios系统提供的UIImageView控件是不支持GIF的加载的,在APP开发中会使用到一些GIF图片,本文主要讲解苹果手机上GIF图使用方法,主要是基于SDWebImage框架。

一、界面显示:

1.先集成SDWebImage及SDWebImage/GIF框架

pod 'SDWebImage'

pod 'SDWebImage/GIF'

2.使用SDWebImage/GIF框架提供的兼容GIF图的控件FLAnimatedImageView

初始化

        _img = [[FLAnimatedImageView alloc] init];

        _img.contentMode = UIViewContentModeScaleAspectFill;

        _img.clipsToBounds = YES;

        _img.backgroundColor = ColorViewBack;

        [self.contentView addSubview:_img];

        [_img makeConstraints:^(MASConstraintMaker *make)

            make.left.right.top.bottom.equalTo(self);

        ];

加载GIF图

   [_img sd_setImageWithURL:[NSUrl urlWithStrint:@"http;xxxxxxx"]] 

该控件的使用方法与系统的UIImageView一样。

二、上传

上传方法可以分为Base64和file方法,本文主要介绍Base 64方法

//图片文件转化成Base64字符

+(NSString *)getGifBase64Str:(NSData *)data



    NSString *imageStyle = [self getImageStyle:data];

    NSString *str = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

    str = [NSString stringWithFormat:@"data:image/%@;base64,%@", imageStyle, str];

    return str;



//获取图片的格式

+(NSString *)getImageStyle:(NSData *)data



    uint8_t c;

    [data getBytes:&c length:1];

    switch (c)

        case 0xFF:

            return @"jpeg";

        case 0x89:

            return @"png";

        case 0x47:

            return @"gif";

        case 0x49:

        case 0x4D:

            return @"tiff";

        case 0x52:

            if ([data length] < 12)

                return nil;

           

            NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding];

            if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"])

                return @"webp";

           

            return nil;

   

    return nil;



把这个转化后的Base64字符串,当成一个网络请求的参数,发起请求即可(要有post请求,Base64字符长度较大,get请求不支持)

三、保存到相册

NSData *gifData = [NSData dataWithContentsOfURL:[NSURL URLWithString:url] options:NSDataReadingUncached error:nil];

    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];

    NSDictionary *metadata = @@"UTI":(__bridge NSString *)kUTTypeGIF;

    [library writeImageDataToSavedPhotosAlbum:gifData metadata:metadata completionBlock:^(NSURL *assetURL, NSError *error)

        [self showAlert:@"保存成功" type:AlertViewType_Toast];

    ] ;

原文链接:https://blog.csdn.net/qq_30356665/java/article/details/88054049

如何在Canvas上显示gif动画 SWT

1、首先,重写控件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, attrs, defStyle);
setViewAttributes(context, attrs, defStyle);


@SuppressLint("NewApi")
private void setViewAttributes(Context context, AttributeSet attrs,
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定义进去,代码如下:

[html] view plain copy
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_
android:layout_
android:orientation="vertical" >

<net.loonggg.gif.view.GifView
android:id="@+id/gif1"
android:layout_
android:layout_
android:layout_gravity="center_horizontal"
android:enabled="false" />

<net.loonggg.gif.view.GifView
android:id="@+id/gif2"
android:layout_
android:layout_
android:layout_gravity="center_horizontal"
android:enabled="false" />

</LinearLayout>

2、最后,在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);



参考技术A 你直接用这条语句就可解决
final JLabel label = new JLabel();
label.setIcon(new ImageIcon("mainback.gif"));
不用去重画什么的.
希望采纳追问

这个是swing的label,可以放在swt的容器里边吗?

参考技术B public class ImageCanvasTest
public static void main(String[] args)
Display display = new Display();
final Shell shell = new Shell(display);
ImageViewer ic = new ImageViewer(shell);

shell.setLayout( new FillLayout());
FileDialog dialog = new FileDialog(shell, SWT.OPEN);
dialog.setText( " Open an image file or cancel " );
String string = dialog.open();

ImageLoader loader = new ImageLoader();
ImageData[] imageDatas = loader.load(string);
if (imageDatas.length == 0 )
return ;
else if (imageDatas.length == 1 )
ic.setImage(imageDatas[ 0 ]);
else
ic.setImages(imageDatas, loader.repeatCount);


ic.pack();
shell.pack();
shell.open();
while ( ! shell.isDisposed())
if ( ! display.readAndDispatch())
display.sleep();

display.dispose();



更详细的教程:http://irving-wei.iteye.com/blog/1090164
参考技术C 将程序显示逻辑和数据部分开,监听数据变化,然后重绘显示组件 参考技术D 1.会根据用途以及变化更符合人体 2.见过一个 第5个回答  2013-04-28 这个需要用多线程控制。 第6个回答  2015-12-16 vmfmj,韩国不好看吧?还比较麻烦!!!

以上是关于iOS GIF动态图(显示、上传、保存)的主要内容,如果未能解决你的问题,请参考以下文章

winform gif图片静态显示问题

动态图GIF动态图怎么做?上传动态效果图到你的csdn?

动态图GIF动态图怎么做?上传动态效果图到你的csdn?

如何在Canvas上显示gif动画 SWT

安卓手机如何制作GIF动态图?

安卓中如何添加显示gif动态图片?