我想绘制一个删除按钮就像主屏幕上的删除应用程序按钮,如下面的代码.
想法是首先画十字架,然后旋转45度.我的代码出了什么问题?
self.deleteButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, BADGE_SIZE, BADGE_SIZE)];
if (!deleteBtnImg) {
CGRect imgFrame = self.deleteButton.bounds;
UIGraphicsBeginImageContextWithOptions(imgFrame.size, NO, 0.0);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGFloat size = MIN(imgFrame.size.width, imgFrame.size.height);
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(imgFrame.size.width/2, imgFrame.size.height/2)
radius:size/2-RADIUS_MARGIN
startAngle:0
endAngle:M_PI * 2
clockwise:YES];
[path moveToPoint:CGPointMake(size / 2, 0)];
[path addLineToPoint:CGPointMake(size / 2, size)];
[path moveToPoint:CGPointMake(0, size / 2)];
[path addLineToPoint:CGPointMake(size, size / 2)];
[[UIColor whiteColor] setFill];
[[UIColor redColor] setStroke];
[path setLineWidth:1.0];
[path fill];
[path stroke];
CGContextRotateCTM(context, M_PI/4);
deleteBtnImg = UIGraphicsGetImageFromCurrentImageContext();
CGContextRestoreGState(context);
UIGraphicsEndImageContext();
}
[self.deleteButton setImage:deleteBtnImg forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)
您必须在开始绘制之前旋转上下文.但即使您在绘图前旋转.图像看起来仍然不正确.这是因为当您旋转上下文时,上下文实际上围绕它的原点旋转,即(0,0)或左下角(CoreGraphic的坐标系与UI略有不同).因此,您可以做的是,在旋转之前,转换上下文以使其围绕其中心旋转,然后在旋转后将其移回.这是一个简单的例子:
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGFloat size = MIN(imgFrame.size.width, imgFrame.size.height);
CGContextTranslateCTM(context, size / 2, size / 2);
CGContextRotateCTM(context, M_PI_4);
CGContextTranslateCTM(context, -size / 2, -size / 2);
// Start your drawing code
Run Code Online (Sandbox Code Playgroud)