我已经尝试过这段代码,但却出现了错误的数字。有时它会点击透明部分并返回值,有时它会点击没有值的彩色部分。
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [[event allTouches] anyObject];
CGPoint location = [touch locationInView:touch.view];
UIColor *color = [self colorAtPosition: location];
const CGFloat* components = CGColorGetComponents(color.CGColor);
NSLog(@"Red: %f", components[0]);
NSLog(@"Green: %f", components[1]);
NSLog(@"Blue: %f", components[2]);
NSLog(@"Alpha: %f", CGColorGetAlpha(color.CGColor));
NSLog(@"x:%f y:%f",location.x,location.y);
}
- (UIColor *)colorAtPosition:(CGPoint)position {
CGRect sourceRect = CGRectMake(position.x, position.y, 1.f, 1.f);
CGImageRef imageRef = CGImageCreateWithImageInRect(self.image.CGImage, sourceRect);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *buffer = malloc(4);
CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big;
CGContextRef context = CGBitmapContextCreate(buffer, 1, 1, 8, 4, colorSpace, bitmapInfo);
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(context, CGRectMake(0.f, 0.f, 1.f, 1.f), imageRef);
CGImageRelease(imageRef);
CGContextRelease(context);
CGFloat r = buffer[0] / 255.f;
CGFloat g = buffer[1] / 255.f;
CGFloat b = buffer[2] / 255.f;
CGFloat a = buffer[3] / 255.f;
free(buffer);
return [UIColor colorWithRed:r green:g blue:b alpha:a];
}
答案 0 :(得分:1)
我已经使用了你的代码,它可以解决一些变化:D! (但我用的是长按手势)
- (void)didRecognizeLogPressGesture:(UILongPressGestureRecognizer*)gesture
{
if (gesture.state == UIGestureRecognizerStateChanged)
{
CGPoint point = [gesture locationInView:self.imageView];
point.x = point.x*self.imageView.image.size.width/self.imageView.bounds.size.width;
point.y = point.y*self.imageView.image.size.height/self.imageView.bounds.size.height;
CGRect sourceRect = CGRectMake(point.x, point.y, 1.f, 1.f);
CGImageRef imageRef = CGImageCreateWithImageInRect(self.imageView.image.CGImage, sourceRect);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *buffer = malloc(4);
CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big;
CGContextRef context = CGBitmapContextCreate(buffer, 1, 1, 8, 4, colorSpace, bitmapInfo);
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(context, CGRectMake(0, 0, 1, 1), imageRef);
CGFloat r = buffer[0] / 255.f;
CGFloat g = buffer[1] / 255.f;
CGFloat b = buffer[2] / 255.f;
CGFloat a = buffer[3] / 255.f;
free(buffer);
self.viewColor.backgroundColor = [UIColor colorWithRed:r green:g blue:b alpha:a];
}
}
主要变化是:
point.x = point.x*self.imageView.image.size.width/self.imageView.bounds.size.width;
point.y = point.y*self.imageView.image.size.height/self.imageView.bounds.size.height;
使用它,您将转换相对于实际图像大小的坐标。