UIImagePickerController не заполняет экран - PullRequest
56 голосов
/ 20 апреля 2010

скриншот http://i39.tinypic.com/oiermb.png

Я добавляю пользовательский оверлей к UIImagePickerController, и в нижней части окна отображается постоянная черная полоса. Вот мой код для создания экземпляра контроллера.

- (UIImagePickerController *)imagePicker {
    if (_imagePicker) {
        return _imagePicker;
    }

    _imagePicker = [[UIImagePickerController alloc] init];
    _imagePicker.delegate = self;

    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        _imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;

        _imagePicker.showsCameraControls = NO;

        _imagePicker.wantsFullScreenLayout = YES;
        _imagePicker.navigationBarHidden = YES;
        _imagePicker.toolbarHidden = YES;

    } else {
        _imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }

    return _imagePicker;
}

Возвращенный контроллер отображается модально и работает просто отлично (то есть отображает полный экран), когда я не скрываю элементы управления камерой.


Благодаря предложению Оле я начал работать с этим кодом:

// Resize the camera preview
        _imagePicker.cameraViewTransform = CGAffineTransformMakeScale(1.0, 1.03);

Увеличение высоты на 3% сработало просто отлично. Когда я добавляю свою пользовательскую панель инструментов внизу экрана, в окне больше не появляется черная полоса.

Ответы [ 11 ]

51 голосов
/ 04 апреля 2013

Масштабирование по фиксированному значению не очень хорошая идея ... так как я уверен, что любой, кто использовал принятый здесь ответ, вероятно, узнал, когда вышел iPhone 5.

Вот фрагмент кода, который можно динамически масштабировать в зависимости от разрешения экрана, чтобы исключить буквенный бокс.

// Device's screen size (ignoring rotation intentionally):
CGSize screenSize = [[UIScreen mainScreen] bounds].size;

// iOS is going to calculate a size which constrains the 4:3 aspect ratio
// to the screen size. We're basically mimicking that here to determine
// what size the system will likely display the image at on screen.
// NOTE: screenSize.width may seem odd in this calculation - but, remember,
// the devices only take 4:3 images when they are oriented *sideways*.
float cameraAspectRatio = 4.0 / 3.0;
float imageWidth = floorf(screenSize.width * cameraAspectRatio);
float scale = ceilf((screenSize.height / imageWidth) * 10.0) / 10.0;

self.ipc.cameraViewTransform = CGAffineTransformMakeScale(scale, scale);
37 голосов
/ 20 апреля 2010

Соотношение сторон камеры составляет 4: 3, соотношение сторон экрана - 3: 2. Таким образом, изображение с камеры просто не может заполнить экран, если вы не хотите обрезать до 3: 2. Для этого примените соответствующее преобразование масштаба.

21 голосов
/ 27 ноября 2013

Эй, я видел, что некоторые люди все еще получали черную полосу внизу после вычисления масштаба для iPhone 5. У меня была эта проблема на некоторое время, но потом я понял, что вам нужно перевести представление так, чтобы оно было посерединеэкрана и затем примените масштаб.Вот мой код для выполнения этих двух вещей, и он работает для меня!

    CGSize screenBounds = [UIScreen mainScreen].bounds.size;

    CGFloat cameraAspectRatio = 4.0f/3.0f;

    CGFloat camViewHeight = screenBounds.width * cameraAspectRatio;
    CGFloat scale = screenBounds.height / camViewHeight;

    m_imagePickerController.cameraViewTransform = CGAffineTransformMakeTranslation(0, (screenBounds.height - camViewHeight) / 2.0);
    m_imagePickerController.cameraViewTransform = CGAffineTransformScale(m_imagePickerController.cameraViewTransform, scale, scale);
10 голосов
/ 11 мая 2014

Из моего опыта работы с iOS 7, iphone 5S, чтобы увидеть центр изображения в полноэкранном предварительном просмотре, нужно объединить преобразования, а не последовательно:

pickerController.cameraOverlayView = self.view;

CGSize screenSize = [[UIScreen mainScreen] bounds].size;   // 320 x 568

float scale = screenSize.height / screenSize.width*3/4;  // screen height divided by the pickerController height ... or:  568 / ( 320*4/3 )

CGAffineTransform translate=CGAffineTransformMakeTranslation(0,(screenSize.height - screenSize.width*4/3)*0.5);
CGAffineTransform fullScreen=CGAffineTransformMakeScale(scale, scale);
pickerController.cameraViewTransform =CGAffineTransformConcat(fullScreen, translate);
10 голосов
/ 18 мая 2010

Преобразуйте это с помощью:

#define CAMERA_TRANSFORM                    1.12412

_picker.wantsFullScreenLayout = YES;
_picker.cameraViewTransform = CGAffineTransformScale(_picker.cameraViewTransform, CAMERA_TRANSFORM, CAMERA_TRANSFORM);
4 голосов
/ 04 января 2017

Это работало для меня на iOS 10:

let screenSize = UIScreen.main.bounds.size
let cameraAspectRatio = CGFloat(4.0 / 3.0)
let cameraImageHeight = screenSize.width * cameraAspectRatio
let scale = screenSize.height / cameraImageHeight
imagePickerController.cameraViewTransform = CGAffineTransform(translationX: 0, y: (screenSize.height - cameraImageHeight)/2)
imagePickerController.cameraViewTransform = imagePickerController.cameraViewTransform.scaledBy(x: scale, y: scale)
4 голосов
/ 07 августа 2015

А вот и ответ в Swift.

let screenSize:CGSize = UIScreen.mainScreen().bounds.size

let ratio:CGFloat = 4.0 / 3.0
let cameraHeight:CGFloat = screenSize.width * ratio
let scale:CGFloat = screenSize.height / cameraHeight

let imag:UIImagePickerController = UIImagePickerController()
imag.cameraViewTransform = CGAffineTransformMakeTranslation(0, (screenSize.height - cameraHeight) / 2.0)
imag.cameraViewTransform = CGAffineTransformScale(imag.cameraViewTransform, scale, scale)
3 голосов
/ 05 сентября 2013

Я использовал этот метод для расчета масштаба.

// get the screen size
CGSize screenSize = [[UIScreen mainScreen] bounds].size;
// establish the height to width ratio of the camera
float heightRatio = 4.0f / 3.0f;
// calculate the height of the camera based on the screen width
float cameraHeight = screenSize.width * heightRatio;
// calculate the ratio that the camera height needs to be scaled by
float scale = screenSize.height / cameraHeight;
imagePicker.cameraViewTransform = CGAffineTransformMakeScale(scale, scale);
2 голосов
/ 13 мая 2014

моя проблема решена:)

//Camera is 426 * 320. Screen height is 568.  Multiply by 1.333 in 5 inch (iPhone5) to fill vertical

CGAffineTransform translate = CGAffineTransformMakeTranslation(0.0, 71.0); //This slots the preview exactly in the middle of the screen by moving it down 71 points
self.imagePickerController.cameraViewTransform = translate;

CGAffineTransform scale = CGAffineTransformScale(translate, 1.333333, 1.333333);
self.imagePickerController.cameraViewTransform = scale;
0 голосов
/ 14 октября 2016
PickerViewController.m    
#define CAMERA_TRANSFORM  1.8

- (void)viewDidAppear:(BOOL)animated
{
 if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
       // type = UIImagePickerControllerSourceTypeCamera;

        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.allowsEditing = NO;
        picker.delegate   = self;
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker.showsCameraControls=NO;
        picker.extendedLayoutIncludesOpaqueBars = YES;
        picker.cameraViewTransform = CGAffineTransformScale(picker.cameraViewTransform, CAMERA_TRANSFORM , CAMERA_TRANSFORM);

        [self presentViewController:picker animated:YES completion:nil];
    }else{

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message"
                                                        message:@"Device have no camera"
                                                       delegate:self
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
    }
}
...