how to sharp/blur an uiimage in iphone?

前端 未结 4 452
傲寒
傲寒 2020-12-19 19:15

I have a view with UIImageView and an UIImage set to it. How do I make image sharp or blur using coregraphics?

4条回答
  •  -上瘾入骨i
    2020-12-19 20:09

    Going down the OpenGL route felt like insane overkill for my needs (blurring a touched point on an image). Instead I implemented a simple blurring process that takes a touch point, creates a rect containing that touch point, samples the image in that point and then redraws the sample image upside down on top of the source rect several times slightly offset with slightly different opacity. This produces a pretty nice poor man's blur effect without an insane amount of code and complexity. Code follows:


    - (UIImage*)imageWithBlurAroundPoint:(CGPoint)point {
        CGRect             bnds = CGRectZero;
        UIImage*           copy = nil;
        CGContextRef       ctxt = nil;
        CGImageRef         imag = self.CGImage;
        CGRect             rect = CGRectZero;
        CGAffineTransform  tran = CGAffineTransformIdentity;
        int                indx = 0;
    
        rect.size.width  = CGImageGetWidth(imag);
        rect.size.height = CGImageGetHeight(imag);
    
        bnds = rect;
    
        UIGraphicsBeginImageContext(bnds.size);
        ctxt = UIGraphicsGetCurrentContext();
    
        // Cut out a sample out the image
        CGRect fillRect = CGRectMake(point.x - 10, point.y - 10, 20, 20);
        CGImageRef sampleImageRef = CGImageCreateWithImageInRect(self.CGImage, fillRect);
    
        // Flip the image right side up & draw
        CGContextSaveGState(ctxt);
    
        CGContextScaleCTM(ctxt, 1.0, -1.0);
        CGContextTranslateCTM(ctxt, 0.0, -rect.size.height);
        CGContextConcatCTM(ctxt, tran);
    
        CGContextDrawImage(UIGraphicsGetCurrentContext(), rect, imag);
    
        // Restore the context so that the coordinate system is restored
        CGContextRestoreGState(ctxt);
    
        // Cut out a sample image and redraw it over the source rect
        // several times, shifting the opacity and the positioning slightly
        // to produce a blurred effect
        for (indx = 0; indx < 5; indx++) {
            CGRect myRect = CGRectOffset(fillRect, 0.5 * indx, 0.5 * indx);
            CGContextSetAlpha(ctxt, 0.2 * indx);
            CGContextScaleCTM(ctxt, 1.0, -1.0);
            CGContextDrawImage(ctxt, myRect, sampleImageRef);
        }
    
        copy = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        return copy;
    }
    

提交回复
热议问题