|
9 | 9 |
|
10 | 10 | #import "XCUIElement+FBUtilities.h" |
11 | 11 |
|
| 12 | +#import <objc/runtime.h> |
| 13 | + |
12 | 14 | #import "FBAlert.h" |
13 | 15 | #import "FBLogger.h" |
14 | 16 | #import "FBMacros.h" |
|
18 | 20 | #import "FBXCodeCompatibility.h" |
19 | 21 | #import "XCAXClient_iOS.h" |
20 | 22 | #import "XCUIElement+FBWebDriverAttributes.h" |
| 23 | +#import "XCUIScreen.h" |
21 | 24 |
|
22 | 25 | @implementation XCUIElement (FBUtilities) |
23 | 26 |
|
@@ -124,4 +127,48 @@ - (BOOL)fb_waitUntilSnapshotIsStable |
124 | 127 | return result; |
125 | 128 | } |
126 | 129 |
|
| 130 | +- (NSData *)fb_screenshotWithError:(NSError **)error |
| 131 | +{ |
| 132 | + if (CGRectIsEmpty(self.frame)) { |
| 133 | + if (error) { |
| 134 | + *error = [[FBErrorBuilder.builder withDescription:@"Cannot get a screenshot of zero-sized element"] build]; |
| 135 | + } |
| 136 | + return nil; |
| 137 | + } |
| 138 | + |
| 139 | + Class xcScreenClass = objc_lookUpClass("XCUIScreen"); |
| 140 | + if (nil == xcScreenClass) { |
| 141 | + if (error) { |
| 142 | + *error = [[FBErrorBuilder.builder withDescription:@"Element screenshots are only available since Xcode9 SDK"] build]; |
| 143 | + } |
| 144 | + return nil; |
| 145 | + } |
| 146 | + |
| 147 | + XCUIScreen *mainScreen = (XCUIScreen *)[xcScreenClass mainScreen]; |
| 148 | + NSData *result = [mainScreen screenshotDataForQuality:1 rect:self.frame error:error]; |
| 149 | + if (nil == result) { |
| 150 | + return nil; |
| 151 | + } |
| 152 | + |
| 153 | + UIImage *image = [UIImage imageWithData:result]; |
| 154 | + UIInterfaceOrientation orientation = self.application.interfaceOrientation; |
| 155 | + UIImageOrientation imageOrientation = UIImageOrientationUp; |
| 156 | + // The received element screenshot will be rotated, if the current interface orientation differs from portrait, so we need to fix that first |
| 157 | + if (orientation == UIInterfaceOrientationLandscapeRight) { |
| 158 | + imageOrientation = UIImageOrientationLeft; |
| 159 | + } else if (orientation == UIInterfaceOrientationLandscapeLeft) { |
| 160 | + imageOrientation = UIImageOrientationRight; |
| 161 | + } else if (orientation == UIInterfaceOrientationPortraitUpsideDown) { |
| 162 | + imageOrientation = UIImageOrientationDown; |
| 163 | + } |
| 164 | + CGSize size = image.size; |
| 165 | + UIGraphicsBeginImageContext(CGSizeMake(size.width, size.height)); |
| 166 | + [[UIImage imageWithCGImage:(CGImageRef)[image CGImage] scale:1.0 orientation:imageOrientation] drawInRect:CGRectMake(0, 0, size.width, size.height)]; |
| 167 | + UIImage *fixedImage = UIGraphicsGetImageFromCurrentImageContext(); |
| 168 | + UIGraphicsEndImageContext(); |
| 169 | + |
| 170 | + // The resulting data is a JPEG image, so we need to convert it to PNG representation |
| 171 | + return (NSData *)UIImagePNGRepresentation(fixedImage); |
| 172 | +} |
| 173 | + |
127 | 174 | @end |
0 commit comments