使用drawInRect时UIImage Aspect Fit? [英] UIImage Aspect Fit when using drawInRect?

查看:238
本文介绍了使用drawInRect时UIImage Aspect Fit?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

UIView提供方面适合内容模式。但是,我是UIView的子类,并希望使用具有宽高比的drawInRect绘制UIImage。有没有办法让我在不使用UIImageView的情况下访问该功能?

UIView provides for the "aspect fit" content mode. However, I've subclasses UIView and would like to draw a UIImage using drawInRect with an aspect fit. Is there any way for me to access that functionality without using a UIImageView?

推荐答案

这个数学有点毛茸茸,但幸运的是,这是我之前准备的解决方案:

The math for that is a little bit hairy, but fortunately, here's a solution I prepared earlier:

- (UIImage *)imageScaledToSize:(CGSize)size
{
    //create drawing context
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f);

    //draw
    [self drawInRect:CGRectMake(0.0f, 0.0f, size.width, size.height)];

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

- (UIImage *)imageScaledToFitSize:(CGSize)size
{
    //calculate rect
    CGFloat aspect = self.size.width / self.size.height;
    if (size.width / aspect <= size.height)
    {
        return [self imageScaledToSize:CGSizeMake(size.width, size.width / aspect)];
    }
    else
    {
        return [self imageScaledToSize:CGSizeMake(size.height * aspect, size.height)];
    }
}

第一个函数相当于scale to fill ,第二个(调用第一个)相当于纵横比。这些方法是作为UIImage上的类别编写的,所以要在另一个类中使用它们,你需要通过将图像作为第二个参数传递来调整它们(或者像我一样在UIImage上创建一个类别)。

The first function is equivalent to "scale to fill", the second (which calls the first) is equivalent to "aspect fit". These methods were written as a category on UIImage so to use them from within another class you'll need to tweak them by passing the image in as a second parameter (or just make a category on UIImage like I did).

这篇关于使用drawInRect时UIImage Aspect Fit?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆