动画背景使用colorWithPatternImage时UIView的颜色

时间:2012-04-17 11:42:26

标签: iphone objective-c ios core-animation

当我为backgroundColor的{​​{1}}属性设置动画时,我正在使用以下代码段:

UIView

这适用于基本颜色(红色,绿色,灰色等),但是,当我尝试使用这样的颜色时: [UIView beginAnimations:@"fade" context:nil]; [UIView setAnimationDuration:1]; [[self view] setBackgroundColor: [UIColor greenColor]; [UIView commitAnimations]; 动画将不起作用,视图将设置其新的背景,但没有所需的淡入淡出动画。

如何为[UIColor colorWithPatternImage:[UIImage imageNamed:@"img1.png"]];设置动画以接受UIView's backgroundColor

提前非常感谢你。

2 个答案:

答案 0 :(得分:2)

我已经更改了我的代码。使用此功能并且它的工作100%...我测试了它..

   //Function which will give you RGB color from your image..(copy and add this function in your code before calling it)
- (UIColor*)getRGBAsFromImage: (UIImage*)image atX: (int)xx andY: (int)yy count: (int)count
{
NSMutableArray *result = [NSMutableArray arrayWithCapacity:count];

// First get the image into your data buffer
CGImageRef imageRef = [image CGImage];
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *rawData = malloc(height * width * 4);
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData, width, height,
                                             bitsPerComponent, bytesPerRow, colorSpace,
                                             kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);

CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
CGContextRelease(context);

// Now your rawData contains the image data in the RGBA8888 pixel format.
int byteIndex = (bytesPerRow * yy) + xx * bytesPerPixel;
UIColor *acolor;
for (int ii = 0 ; ii < count ; ++ii)
{
    CGFloat red = (rawData[byteIndex] * 1.0) / 255.0;
    CGFloat green = (rawData[byteIndex + 1] * 1.0) / 255.0;
    CGFloat blue = (rawData[byteIndex + 2] * 1.0) / 255.0;
    CGFloat alpha = (rawData[byteIndex + 3] * 1.0) / 255.0;
    byteIndex += 4;

    acolor = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
    [result addObject:acolor];
}

free(rawData);
return acolor;
}


// Here, the code for animation that you want..use it and enjoy..
UIImage *image = [UIImage imageNamed:@"Black.png"];
    UIColor *color=  [self getRGBAsFromImage:image atX:100 andY:100 count:1];
    [UIView beginAnimations:@"fade" context:nil];
    [UIView setAnimationDuration:1];
    [[self view] setBackgroundColor: color];
    [UIView commitAnimations];

它工作正常......希望这会对你有帮助......

答案 1 :(得分:2)

我想在动画所需的步骤中使用的所有颜色都是在起始RGB颜色和结束RGB颜色之间具有分量RGB值的颜色......

但当然,如果你使用图像那是不可能的......

所以尝试一种解决方法,就像使用alpha = 0到alpha = 1的淡入的第二个临时uiview一样  值变化...