top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

UIImageView center and aspect fit

+1 vote
440 views

I have added an image view and setting the image to it programmatically.
I am unable to set the image to center and aspect fit the image view.
In other words, I simply want that:
Scale down to fit the image, if the image is larger in size.
Center if small in size.

posted Feb 6, 2018 by Dhanalakshmi K

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

You can achieve this by setting content mode of image view to UIViewContentModeScaleAspectFill.

Then use following method method to get the resized uiimage object.

- (UIImage*)setProfileImage:(UIImage *)imageToResize onImageView:(UIImageView *)imageView
{
    CGFloat width = imageToResize.size.width;
    CGFloat height = imageToResize.size.height;
    float scaleFactor;
    if(width > height)
    {
        scaleFactor = imageView.frame.size.height / height;
    }
    else
    {
        scaleFactor = imageView.frame.size.width / width;
    }

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(width * scaleFactor, height * scaleFactor), NO, 0.0);
    [imageToResize drawInRect:CGRectMake(0, 0, width * scaleFactor, height * scaleFactor)];
    UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return resizedImage;
}

Swift Version

func setProfileImage(imageToResize: UIImage, onImageView: UIImageView) -> UIImage
{
    let width = imageToResize.size.width
    let height = imageToResize.size.height

    var scaleFactor: CGFloat

    if(width > height)
    {
        scaleFactor = onImageView.frame.size.height / height;
    }
    else
    {
        scaleFactor = onImageView.frame.size.width / width;
    }

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(width * scaleFactor, height * scaleFactor), false, 0.0)
    imageToResize.drawInRect(CGRectMake(0, 0, width * scaleFactor, height * scaleFactor))
    let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return resizedImage;
}
answer Mar 12, 2018 by Mamatha M
Similar Questions
+1 vote

How to set image for UIImageView in UITableViewCell Asynchronously for each cell.

+1 vote

Building an iOS app for reading articles. I’m using Facebook SDK to share the article link and image on Facebook.

This is the process:

  1. After clicking on bar button item on top right, UIActivityViewController gets opened on the bottom of the screen which gives option to share via fb, google , linked in etc.

  2. On clicking the Facebook button in UIActivityVIewController, default screen opens for sharing but ideally fb SDK code should get executed.

The following "if condition” does not executed.

  [AVC setCompletionHandler:^(NSString *activityType, BOOL completed)

 {
    if([activityType isEqualToString: UIActivityTypePostToFacebook]){
     FBLinkShareParams *params = [[FBLinkShareParams alloc] init];
  1. But when clicked on the cancel button of the default screen, “if condition" gets executed and app is able to share the article as expected.

Here is the code.

- (IBAction)ysshareAction:(id)sender {

NSURL *Imageurl = [NSURL URLWithString:_DetailModal1[2]];
NSData *data =  [NSData dataWithContentsOfURL:Imageurl];

UIImage *image = [[UIImage alloc] initWithData:data];

      NSURL *linkURL = [NSURL URLWithString:_DetailModal1[4]];//article url

 NSMutableAttributedString *stringText = [[NSMutableAttributedString alloc] initWithString:_DetailModal1[0]];//_DetailModal1[0] contain article title////
  [stringText addAttribute:NSLinkAttributeName value:linkURL range:NSMakeRange(0, stringText.length)];

NSArray *itemArrany = @[stringText,image,];//title is displayed but not as hyperlink.
  UIActivityViewController *AVC = [[UIActivityViewController alloc] initWithActivityItems:itemArrany applicationActivities:nil];
   AVC.excludedActivityTypes=@[];
   [AVC setCompletionHandler:^(NSString *activityType, BOOL completed)

  {
   if([activityType isEqualToString: UIActivityTypePostToFacebook]){

          FBLinkShareParams *params = [[FBLinkShareParams alloc] init];
          params.link = [NSURL URLWithString:@"https://www.youtube.com/watch?v=pa8lsBNG31c"];
                //    // If the Facebook app is installed and we can present the share dialog
        if ([FBDialogs canPresentShareDialogWithParams:params]) {

            // Present share dialog
            [FBDialogs presentShareDialogWithLink:params.link
                                          handler:^(FBAppCall *call, NSDictionary *results, NSError *error) {
                                              if(error) {
                                                  // An error occurred, we need to handle the error
                                                  // See: https://developers.facebook.com/docs/ios/errors
                                                  NSLog(@"Error publishing story: %@", error.description);
                                              } else {
                                                  // Success
                                                  NSLog(@"result %@", results);
                                              }
                                          }];

            // If the Facebook app is NOT installed and we can't present the share dialog
        } else {
            // FALLBACK: publish just a link using the Feed dialog

            // Put together the dialog parameters
            NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                       @"YourStory", @"name",
                                           _DetailModal1[0], @"caption",
                                           _DetailModal1[4], @"link",
                                           _DetailModal1[2], @"picture",
                                           nil];

            // Show the feed dialog
            [FBWebDialogs presentFeedDialogModallyWithSession:nil
                                                   parameters:params
                                                      handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
                                                        if (error) {
                                                              // An error occurred, we need to handle the error
                                                              // See: https://developers.facebook.com/docs/ios/errors
                                                              NSLog(@"Error publishing story: %@", error.description);
                                                          } else {
                                                              if (result == FBWebDialogResultDialogNotCompleted) {
                                                                  // User canceled.
                                                                  NSLog(@"User cancelled.");
                                                              } else {
                                                                  // Handle the publish feed callback
                                                                  //   NSDictionary *urlParams = [self parseURLParams:[resultURL query]];

                                                                  //  if (![urlParams valueForKey:@"post_id"]) {
                                                                  // User canceled.
                                                                  NSLog(@"User cancelled.");

                                                                  //    } else {
                                                                  // User clicked the Share button
                                                                  //         NSString   *result = [NSString stringWithFormat: @"Posted story, id: %@", [urlParams valueForKey:@"post_id"]];
                                                                 //        
                                                              }
                                                          }



                                                      }];


        }
           }
            }];
 [self presentViewController:AVC animated:YES completion:nil];
      }

Any help is really appreciated.

0 votes

Here i want to know any simple way to check whether NSMutableArray contains specified object. I used for loop to find the object at index is same or not, but its get sucks processing because my array contains plenty of objects.

+1 vote

I want to check specified table contains value or its empty. I used number of complex method to find but no luck, any body can help me.

...