简体   繁体   English

根据其子视图设置主视图的大小

[英]Set the size of Main View according to its subView

I have a Main View with frame 我有带框架的主视图

0, 60, 768, 1024, 0、60、768、1024,

It has many views as subView. 它有许多视图作为subView。 First subview is an UIImageView . 第一个子视图是UIImageView The property associated with ImageView is AspectFit. 与ImageView关联的属性是AspectFit。 Now I want to take screenshot of the only part of screen which bounds that of UIImageView (There are at least 4-5 Subviews which CAN or can not be above This UIImageView) The standard coding given by iPhone has been used here. 现在,我想截取屏幕上唯一与UIImageView绑定的部分的屏幕截图(至少有4-5个子视图,可以或不能位于此UIImageView之上)这里使用了iPhone提供的标准编码。 The image i get is of Main View. 我得到的图像是主视图。 Now to get only screenshot of UIImageView and whatever above is, I need to set the dimension of my main view to envelop only UIImageView. 现在,仅获取UIImageView的屏幕快照以及以上内容,我需要将主视图的尺寸设置为仅包围UIImageView。

Suppose The image size is 100,100. 假设图像尺寸为100,100。 When I press button, How should I set the Bounds/fRAME OF my mainView? 当我按下按钮时,应如何设置Bounds/fRAMEBounds/fRAME框架? Or In other terms how can I get the frame of UIImageView relative to self.view 或者换句话说,如何获得UIImageView相对于self.view的框架

Instead of changing the frame of main view, try to calculate coordinates of the UIImageView . 而不是更改主视图的框架,请尝试计算UIImageView坐标。

Assume that frames of your main view and image view are (0, 60, 768, 1024) and (20, 20, 100, 100), respectively. 假设主视图和图像视图的帧分别为(0、60、768、1024)和(20、20、100、100)。

So frame of your image view with respect to global coordinate system is (20, 80, 100, 100). 因此,相对于全局坐标系,图像视图的框架为(20,80,100,100)。 Just add x, y coordinates of main view to its subviews to achieve this. 只需将主视图的x,y坐标添加到其子视图即可实现此目的。 Then, you may get the screenshot of desired frame. 然后,您可以获取所需帧的屏幕截图。

One way would be to grab the entire view's image, then crop it. 一种方法是获取整个视图的图像,然后裁剪它。 No reframing needed. 无需重新构建。 Combining best answers from here and here , it might look like this: 结合此处此处的最佳答案,可能看起来像这样:

- (UIImage *)imageWithView:(UIView *)view croppedBy:(CGRect)rect {

    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], rect);
    UIImage *result = [UIImage imageWithCGImage:imageRef]; 
    CGImageRelease(imageRef);
    return result;
}

For your app, call it like this (assuming we're in a view controller): 对于您的应用程序,可以这样调用它(假设我们在视图控制器中):

UIImage *justMyImageView = [self imageWithView:self.view croppedBy:self.myImageView.frame];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM