IOS:使用 .png 在 View 中着色
<p><p>我有这个代码:</p>
<pre><code>-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
mouseSwiped = YES;
UITouch *touch = ;
CGPoint currentPoint = ;
UIGraphicsBeginImageContext(drawImage.frame.size);
;
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;
}
</code></pre>
<p>使用此代码,我用黑线在 View 中着色,但我想用特定的 png 着色(例如,作为画笔);并具有特定的效果;我应该做些什么改变?</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>我编写了一个从图像中的 CGPoint 获取颜色的方法:
ImageOperations.h:</p>
<pre><code>+ (UIColor *)getColorFromImage:(UIImage*)image atX:(int)x andY:(int)y;
</code></pre>
<p>ImageOperations.m</p>
<pre><code>+ (UIColor *)getColorFromImage:(UIImage*)image atX:(int)x andY:(int)y {
CGImageRef imageRef = ;
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 * 1.0) / 255.0;
CGFloat green = (rawData * 1.0) / 255.0;
CGFloat blue= (rawData * 1.0) / 255.0;
CGFloat alpha = (rawData * 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;
}
</code></pre>
<p>方法调用如下所示:</p>
<pre><code>UIColor *myColor= ;
self.myView.backgroundColor = myColor;
</code></pre>
<p>希望这会有所帮助。</p></p>
<p style="font-size: 20px;">关于IOS:使用 .png 在 View 中着色,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/9802036/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/9802036/
</a>
</p>
页:
[1]