0

当我拖动滑块时,我正在为我的滑块使用此代码为 UISlider 裁剪图像,然后图像是模糊的

- (UIImage *) revealedTrackImageForCurrentValues {
    //Get left and right x positions
    float lowerHandleWidth = _lowerHandleHidden ? 2.0f : _lowerHandle.frame.size.width;
    float upperHandleWidth = _upperHandleHidden ? 2.0f : _upperHandle.frame.size.width;
    float xLowerValue = ((self.bounds.size.width - lowerHandleWidth) * (_lowerValue - _minimumValue) / (_maximumValue - _minimumValue))+(lowerHandleWidth/2.0f);
    float xUpperValue = ((self.bounds.size.width - upperHandleWidth) * (_upperValue - _minimumValue) / (_maximumValue - _minimumValue))+(upperHandleWidth/2.0f);

    //Crop the image
    CGRect croppedImageRect = CGRectMake(xLowerValue, 0.0f, xUpperValue - xLowerValue, self.trackImage.size.height);
    CGImageRef croppedImageRef = CGImageCreateWithImageInRect([self.trackImage CGImage], croppedImageRect);
    UIImage *croppedImage = [UIImage imageWithCGImage:croppedImageRef];
    CGImageRelease(croppedImageRef);

    return croppedImage;

}

我怎样才能在不损失图像清晰度的情况下做到这一点?

4

1 回答 1

1

编辑代码:

你必须继承 UIImage:

UIImageView+裁剪.h

#import <UIKit/UIKit.h>

@interface UIImage (Cropping)
- (UIImage *)revealedTrackImageForRect:(CGRect)croppedImageRect;
@end

UIImageView+裁剪.m

#import "UIImage+Cropping.h"

@implementation UIImage (Cropping)


- (UIImage *)revealedTrackImageForRect:(CGRect)croppedImageRect
{
    //create drawing context
    UIGraphicsBeginImageContextWithOptions(croppedImageRect.size, NO, 0.0f);

    //draw
    [self drawAtPoint:CGPointMake(-croppedImageRect.origin.x, -croppedImageRect.origin.y)];

    //capture resultant image
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    //return image
    return image;
}

@end

然后调用你的代码:

#import "UIImage+Cropping.h"

- (UIImage *)revealedTrackImageForCurrentValues 
{
    //Get left and right x positions
    float lowerHandleWidth = _lowerHandleHidden ? 2.0f : _lowerHandle.frame.size.width;
    float upperHandleWidth = _upperHandleHidden ? 2.0f : _upperHandle.frame.size.width;
    float xLowerValue = ((self.bounds.size.width - lowerHandleWidth) * (_lowerValue - _minimumValue) / (_maximumValue - _minimumValue))+(lowerHandleWidth/2.0f);
    float xUpperValue = ((self.bounds.size.width - upperHandleWidth) * (_upperValue - _minimumValue) / (_maximumValue - _minimumValue))+(upperHandleWidth/2.0f);

    // Get rect
    CGRect croppedImageRect = CGRectMake(xLowerValue, 0.0f, xUpperValue - xLowerValue, self.trackImage.size.height);

    //Get cropped image
    UIImage *croppedImage = [self.trackImage revealedTrackImageForRect: croppedImageRect];

    return croppedImage;
}
于 2014-09-10T17:00:03.593 回答