4

backgroundColor当我为 a 的属性设置动画时,我正在使用以下代码片段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接受colorWithPatternImage

非常感谢你。

4

2 回答 2

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];

效果很好……希望对你有帮助……

于 2012-04-17T11:57:07.163 回答
2

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

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

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

于 2012-04-17T12:00:07.200 回答