我有这个代码:
-(void)touchesMovedNSSet *)touches withEventUIEvent *)event {
mouseSwiped = YES;
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:drawImage];
UIGraphicsBeginImageContext(drawImage.frame.size);
[drawImage.image drawInRect:CGRectMake(0, 0, drawImage.frame.size.width, drawImage.frame.size.height)];
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 15.0);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0, 0, 0, 1.0); //black
CGContextBeginPath(UIGraphicsGetCurrentContext());
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());
drawImage.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
lastPoint = currentPoint;
}
使用此代码,我用黑线在 View 中着色,但我想用特定的 png 着色(例如,作为画笔);并具有特定的效果;我应该做些什么改变?
Best Answer-推荐答案 strong>
我编写了一个从图像中的 CGPoint 获取颜色的方法:
ImageOperations.h:
+ (UIColor *)getColorFromImageUIImage*)image atXint)x andYint)y;
ImageOperations.m
+ (UIColor *)getColorFromImageUIImage*)image atXint)x andYint)y {
CGImageRef imageRef = [image CGImage];
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *rawData = calloc(height * width * 4, sizeof(unsigned char));
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);
int byteIdx = (bytesPerRow * y) + x * bytesPerPixel;
CGFloat red = (rawData[byteIdx] * 1.0) / 255.0;
CGFloat green = (rawData[byteIdx + 1] * 1.0) / 255.0;
CGFloat blue = (rawData[byteIdx + 2] * 1.0) / 255.0;
CGFloat alpha = (rawData[byteIdx + 3] * 1.0) / 255.0;
byteIdx += 4;
UIColor *acolor = [UIColor colorWithRed:red/255.f
green:green/255.f
blue:blue/255.f
alpha:alpha/255.f];
free(rawData);
return acolor;
}
方法调用如下所示:
UIColor *myColor= [ImageOperations getColorFromImage:myImage atX:cgPoint.x andY:cgPoint.y];
self.myView.backgroundColor = myColor;
希望这会有所帮助。
关于IOS:使用 .png 在 View 中着色,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/9802036/
|