旋转UIImage时像素密度低

时间:2016-02-08 06:39:15

标签: objective-c uiimage

我已经为我们的应用程序找到了一些算法来在MKMapView上旋转注释,并且在每个算法中,图像的像素密度都会崩溃。以下是绿色箭头注释的示例: Green arrow annotation example

Algorithm

也许有人知道算法或扩展来执行正确的图像旋转?

1 个答案:

答案 0 :(得分:1)

而不是UIGraphicsBeginImageContext,使用UIGraphicsBeginImageContextWithOptions为最后一个参数为零。这将最大化屏幕分辨率以匹配您设备的屏幕(例如视网膜)。

即使您创建了视网膜分辨率图像,当您旋转位图时,您也会引入一些进一步的像素化。如果您自己绘制它(例如在注释视图的子类的drawRect中),您可能会获得更清晰的结果:

@interface CustomUserAnnotationView : MKAnnotationView

@property (nonatomic) CGFloat angle;
@property (nonatomic) CGFloat lineWidth;
@property (nonatomic, strong) UIColor *strokeColor;
@property (nonatomic, strong) UIColor *fillColor;

@end

@implementation CustomUserAnnotationView

- (instancetype)initWithAnnotation:(id<MKAnnotation>)annotation reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithAnnotation:annotation reuseIdentifier:reuseIdentifier];

    if (self) {
        self.lineWidth = 2;
        self.strokeColor = [UIColor lightGrayColor];
        self.fillColor = [UIColor greenColor];
        self.backgroundColor = [UIColor clearColor];
        self.frame = CGRectMake(0, 0, 50, 50);            
    }

    return self;
}

// you should probably `setNeedsDisplay` on the other properties' setters, too, but I'm assuming angle is the only one we're worried about right now.

- (void)setAngle:(CGFloat)angle {
    _angle = angle;
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect {
    CGPoint center = CGPointMake(self.bounds.size.width / 2.0, self.bounds.size.height / 2.0);
    CGFloat radius = (MIN(self.bounds.size.width, self.bounds.size.height) - self.lineWidth) / 2.0;

    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:   [self pointAtRadius:radius       percentAngle:0.0 center:center angleOffset:self.angle]];
    [path addLineToPoint:[self pointAtRadius:radius       percentAngle:0.4 center:center angleOffset:self.angle]];
    [path addLineToPoint:[self pointAtRadius:radius * 0.6 percentAngle:0.5 center:center angleOffset:self.angle]];
    [path addLineToPoint:[self pointAtRadius:radius       percentAngle:0.6 center:center angleOffset:self.angle]];
    [path closePath];
    path.lineWidth = self.lineWidth;
    path.lineJoinStyle = kCGLineJoinRound;

    [self.fillColor setFill];
    [path fill];

    [self.strokeColor setStroke];
    [path stroke];
}

- (CGPoint)pointAtRadius:(CGFloat)radius percentAngle:(CGFloat)percentAngle center:(CGPoint)center angleOffset:(CGFloat)angleOffset {
    CGFloat angle = M_PI * 2.0 * percentAngle + angleOffset;
    return CGPointMake(center.x + radius * sin(angle), center.y - radius * cos(angle));
}

@end

enter image description here