我有一个小的代码模块,应该称为签名面板,以便用户可以用手指在此面板上签名。整个过程都在iPad上运行。
现在,我设法执行通常的touchesBegan(),touchesMoved(),touchesEnded()轮播,以使他在该面板上签名。签名时,我在主视图上绘制他的签名。但是,由于某种原因,图像会出现两次:一次正确,一次上下颠倒在主签名上方(参见图片)。由于我在代码中看不到任何翻译,因此我怀疑整个代码可能不正确,但我不知道为什么。有人知道我在做什么错吗?
#import "RMSignatureView.h"
#import <QuartzCore/QuartzCore.h>
@interface RMSignatureView() {
CGPoint origin;
}
-(void) setupLayer;
@property (nonatomic, retain) UIImage* image;
@end
@implementation RMSignatureView
@synthesize image;
-(void) dealloc {
[image release];
[super dealloc];
}
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self setupLayer];
}
return self;
}
-(id) initWithCoder:(NSCoder *)aDecoder {
if ([super initWithCoder:aDecoder] == self) {
[self setupLayer];
}
return self;
}
-(void) setupLayer {
self.layer.cornerRadius = 10;
self.layer.borderColor = [UIColor colorWithRed:109.0/256.0 green:149.0/256.0 blue:224.0/256.0 alpha:1.0].CGColor;
self.layer.borderWidth = 0.5f;
}
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextSetStrokeColorWithColor(context, [UIColor grayColor].CGColor);
CGFloat sizes[2];
sizes[0] = 1;
sizes[1] = 1;
CGContextSetLineDash(context, 0, sizes, 2);
CGContextMoveToPoint(context, rect.origin.x + 50, rect.origin.y + rect.size.height - 30);
CGContextAddLineToPoint(context, rect.origin.x + rect.size.width - 50, rect.origin.y + rect.size.height - 30);
CGContextStrokePath(context);
CGContextSetLineDash(context, 0, NULL, 0);
if (image)
CGContextDrawImage(context, rect, image.CGImage);
CGContextRestoreGState(context);
}
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch* touch = [touches anyObject];
origin = [touch locationInView:self];
}
-(void) touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
origin.x = -1;
origin.y = -1;
}
-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
origin.x = -1;
origin.y = -1;
}
-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch* touch = [touches anyObject];
if (origin.x != -1 && origin.y != -1) {
UIGraphicsBeginImageContext(self.frame.size);
@try {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
if (image)
CGContextDrawImage(context, CGRectMake(0, 0, self.frame.size.width, self.frame.size.height), image.CGImage);
CGContextMoveToPoint(context, origin.x, origin.y);
origin = [touch locationInView:self];
CGContextAddLineToPoint(context, origin.x, origin.y);
CGContextStrokePath(context);
self.image = UIGraphicsGetImageFromCurrentImageContext();
CGContextRestoreGState(context);
}
@finally {
UIGraphicsEndImageContext();
}
}
[self setNeedsDisplay];
}
@end
最佳答案
找到了。石英在左下角而不是左上角具有(0,0)。
关于ios - CGContext陌生,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7672230/