由于需要渲染来自网络的视频数据,自己写了一个类,利用UIImageView来完成此功能。
VideoRender.h
//
// VideoRender.h
//
// Created by apple on 11-5-12.
// Copyright 2011 . All rights reserved.
//
#import <Foundation/Foundation.h>
@interface VideoRender:NSObject {
NSThread *workThread_;
BOOL isRunning_;
NSUInteger width_, height_;
unsigned char* imageData_;
UIImage* image_;
UIImageView* imageView_;
}
-(id)init:(UIImageView*)view width:(NSUInteger)width height:(NSUInteger)height;
-(void)run;
-(void)stop;
@end
VideoRender.mm
//
// VideoRender.mm
//
// Created by apple on 11-5-12.
// Copyright 2011 . All rights reserved.
//
#import "VideoRender.h"
@implementation VideoRender
-(id)init:(UIImageView*)view width:(NSUInteger)width height:(NSUInteger)height {
self = [super init];
imageView_ = view;
width_ = width;
height_ = height;
imageData_ = (unsigned char*)malloc(width_*height_*4);
workThread_ = nil;
isRunning_ = FALSE;
image_ = nil;
return self;
}
-(void)dealloc {
free(imageData_);
if(workThread_ != nil)
[workThread_ release];
if(image_ != nil)
{
[image_ release];
image_ = nil;
}
[super dealloc];
NSLog(@"[video render delloc]");
}
-(void)Render {
if(image_ != nil)
{
[imageView_ setImage:image_];
[image_ release];
image_ = nil;
}
}
-(void)fillData:(NSUInteger)index {
memset(imageData_, index, width_*height_*4);
}
-(void)workThreadProc {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
NSUInteger index = 0;
while (isRunning_)
{
if(image_ != nil) continue;
[NSThread sleepForTimeInterval:0.1];
[self fillData:index];
index++;
if(index >= 256)
index = 0;
CGContextRef ctxRef = CGBitmapContextCreate (imageData_,// 4
width_,
height_,
8, // bits per component
4*width_,
colorSpace,
kCGImageAlphaPremultipliedLast
);
CGImageRef imageRef_ = CGBitmapContextCreateImage(ctxRef);
CGContextRelease(ctxRef);
image_ = [[UIImage alloc] initWithCGImage:imageRef_];
[self performSelectorOnMainThread:@selector(Render) withObject:nil waitUntilDone:TRUE];
CFRelease(imageRef_);
}
CFRelease(colorSpace);
[pool release];
}
-(void)run {
if(workThread_ == nil)
{
isRunning_ = TRUE;
workThread_ = [[NSThread alloc] initWithTarget:self selector:@selector(workThreadProc) object:nil];
[workThread_ start];
}
}
-(void)stop {
if(workThread_ != nil)
{
isRunning_ = FALSE;
[workThread_ cancel];
}
}
@end
附带一个Demo,下载页面 http://download.csdn.net/detail/xunxunnuaa/4156264。