brandontreb.com Tips And Resources For Software Consultants

Case Of The Mondays

Mondays…

The other day, I was faced with an interesting programming challenge and wanted to share my solution. I just submitted a pretty interesting app to the app store that does a number of things (more details soon). Among those things is the ability to generate a calendar.

The Problem

Generating the calendar was the easy part, however when displayed, I wanted it to highlight every Monday of the month. This turned out to be a bit trickier than I imagined.

Really the main challenge here was to determine which day contained the first Monday of the month. After that, we just loop incrementing by 7 and are done.

Looking At The Date Helpers

Looking at what I had to work with in NSDate, NSCalendar, and NSDateComponents, I really found only 2 things that could help me. From NSDateComponents, I could figure out the current day (numeric) and the current day of the week (numeric). Knowing this information was very important.

The Solution

Having the current day and day of the week allowed me to find the date of the Monday on the current week. This was the first challenge as demonstrated below. Assume weekdayComponents is the NSDateComponents generated from the current date.

<code class=’objc’>NSInteger weekday = [weekdayComponents weekday];
NSInteger day         = [weekdayComponents day];

// First, find how many days we are from Monday
int daysAwayFromMonday = weekday - 2;

// Now resolve the monday of this week
int mondayThisWeek = day - daysAwayFromMonday;

// Check if monday this week falls in last month
if(mondayThisWeek <= 0) {
    mondayThisWeek = day + (7 - daysAwayFromMonday);
}</code>

mondayThisWeek will now contain the day number of the Monday of the current week. If that Monday falls on the previous month, mondayThisWeek will be negative. Line 12 resolves that by carrying it into next week.

Finally, we just loop subtracting 7 from that Monday until mondayThisWeek is less than 7 to get the first Monday of the month.

<code class=’objc’>while(mondayThisWeek > 7) {
    mondayThisWeek -= 7;
}</code>

And there you have it. mondayThisWeek (improperly named at this point) will contain the day number of the first Monday for the current month.

So, this was quite a round-a-bout way to find this value. If you have a better solution, please feel free to trash on mine in the comments 😉 .

Farewell (For Now) iDevBlogADay

Hey guys,

I wanted to thank everyone for letting me be a part of the iDevBlogADay community. You guys have been super supportive and I really appreciate all of the commenting, retweeting, and upvoting of my iDevBlogADay articles.

I have found myself in a position with life (work + family) where I may no longer be able to consistently write a post per week. So, after 2 months of writing, it is time for me to pass the torch to the next blogger on the list.

I will still continue to blog (and continue my Twitter For Mac Series), so I really encourage you to subscribe to my RSS feed (or Twitter feed).

Thanks again and Happy Coding!

AppBlogger: A Tool For iOS App Developers And Bloggers

Imagine that you have just found the coolest app in the world and just can’t wait to tell all of your followers about it. So, you head to the admin panel of your blogging engine (hopefully WordPress) and begin to write your review. Now, you want to insert some screenshots, icons, descriptions, app store links, etc… So, what do you do? You head on over to Bing and type in google.com. Next, you search your app name and hopefully find the iTunes URL so that you can slowly grab some information about the app. #Fail

Dum duh dum duh (trumpet noises)!

Enter AppBlogger. AppBlogger is a little tool that I have been working on that uses “Instant Search” technology (jquery fanciness) to allow you to instantly search the app store and quickly get the information you need.

How Does It Work? (you say)

As you start typing, AppBlogger makes an asynchronous request to the iTunes web service and pulls a list of applications that match your search terms. This list is presented as a bunch of icons. You will then click on one of these icons to pull of the details page of that application.

The details page (see above screenshot) then contains everything you need to write a stellar blog post about that application. It provides text fields (for easy copy and paste) with icon URLs, download URL, and screenshot URLs.

I have some plans to integrate this in the near future with my Link Share tool to auto generate shortened URLs that contain your affiliate code (so you can make $). If you have any other suggestions for it, I would love to hear them.

I know many of you are heartbroken and were expecting the next iteration of my Twitter Client For Mac series. I want you to know, you are not forgotten and I will continue the series next Thursday. So Stay Tuned!

Check out AppBlogger!

This post is part of iDevBlogADay, a group of indie iOS development blogs featuring two posts per day. You can keep up with iDevBlogADay through the web site, RSS feed, or Twitter.

Image Manipulation: Retrieving And Updating Pixel Values For A UIImage

Grayscale Jobs

With the recent success of cool photo manipulation apps such as Camera+ and Instagram, it got me wondering. How do these photo apps modify the pixel data of the image.

After doing a bit of research on the subject, I found countless posts on Stack Overflow and the Developer forums about various methods to get and set the pixel values of a UIImage. Most of them unanswered or partially answered. I tested out many solutions and banged my head on my computer into the whee hours of the morning with no success. Every solution I tried seemed to completely destroy the image.

It wasn’t until this morning, I had an “aha” moment, changed one line of code and was able to produce a grayscale version of a UIImage.

Having the ability to get and set pixel values of a UIImage is super important if you want to create a photo related app that has “Filters”. Once you know the basics, you can apply your ninja math skillz to implement cool filter algorithms on the pixels. Below, I will show you onc such algorithm for converting an image to grayscale (it’s not that clever).

I should note, that a good majority of my code comes from Olie’s solution on this Stack Overflow post. His example simply returns and array of UIColor objects for a given image. Mine will modify those colors and write them back to a UIImage.

Converting A UIImage Into A Pixel Array

Here is the first part of our grayscale method. It is creating a char array from a global UIImage property named workingImage.

<code class=’objc’>- (IBAction) grayscale:(id) sender {
    CGContextRef ctx;
    CGImageRef imageRef = [self.workingImage CGImage];
    NSUInteger width = CGImageGetWidth(imageRef);
    NSUInteger height = CGImageGetHeight(imageRef);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    unsigned char *rawData = malloc(height * width * 4);
    NSUInteger bytesPerPixel = 4;
    NSUInteger bytesPerRow = bytesPerPixel * width;
    NSUInteger bitsPerComponent = 8;
    CGContextRef context = CGBitmapContextCreate(rawData, width, height,
    bitsPerComponent, bytesPerRow, colorSpace,
    kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    CGColorSpaceRelease(colorSpace);

    CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
    CGContextRelease(context);
    .
    .
    .</code>

This is a lot of Core Graphics fanciness that isn’t super important to understand. It’s just getting the RGBA values from the image and writing them into the rawData char array. There are 4 bytes per pixel (red, green, blue, alpha), so this array contains 4 * height * width elements.

Modifying The Pixels of a UIImage

Here is where the magic happens. You can replace this code with the logic necessary to apply the filter you are making. Another clever way to approach this would be to pass this code in as a block into the method (I’ll leave that as an exercise for the reader :)).

<code class=’objc’>.
.
.
    int byteIndex = 0;
    for (int ii = 0 ; ii < width * height ; ++ii)
    {
    int outputColor = (rawData[byteIndex] + rawData[byteIndex+1] +
        rawData[byteIndex+2]) / 3;

    rawData[byteIndex] = (char) (outputColor);
    rawData[byteIndex+1] = (char) (outputColor);
    rawData[byteIndex+2] = (char) (outputColor);

        byteIndex += 4;
    }

.
.
.</code>

The first part is pretty straight forward, we have a for loop that goes from 0 to width * height. We index into the rawData array using a counter that we increment by 4 each time (remember 4 bytes per pixel). As you can imagine, the first pixel (rawData[byteIndex]) represents the red pixel, then green for +1, blue for +2, and finally alpha for +3. Note that the alpha byte is last because kCGImageAlphaPremultipliedLast flag above.

In order to do grayscale, we simple set all of the color values to the average color value. So, for example the color [218,232,244] (which is the light blue color of the WordPress editor’s toolbar) would be converted to [231,231,231] which is a fairly light gray color.

The most important step that everyone in the forums seemed to miss was casting the new value to a char. Remember we are using a char array, setting ints as values will generally screw up your image. (This was my “aha” moment that I mentioned above)

Writing The Pixels Back To a UIImage

The final step is to write the pixel data back to a UIImage. Again, I borrowed some of this code from somewhere else and unfortunately lost the link. If I find it, I will update the post.

<code class=’objc’>.
.
.
    ctx = CGBitmapContextCreate(rawData,
        CGImageGetWidth( imageRef ),
        CGImageGetHeight( imageRef ),
        8,
        CGImageGetBytesPerRow( imageRef ),
        CGImageGetColorSpace( imageRef ),
        kCGImageAlphaPremultipliedLast ); 

    imageRef = CGBitmapContextCreateImage (ctx);
    UIImage* rawImage = [UIImage imageWithCGImage:imageRef];  

    CGContextRelease(ctx);  

    self.workingImage = rawImage;  

    free(rawData);
}</code>

All we are doing here is creating a new Bitmap Context, writing it to our CGImageRef and constructing a new UIImage from that CGImageRef. Finally, we just update our workingImage with the modified one. Fancy, I know…

Now, much of this code is to work with my example (download below), but it could easily be tweaked to fit within your super awesome photo app. If you have any questions or comments PLEASE leave them here or send them to me on Twitter (but probably leave them here 😉 ).

Download The Sample Source Project

  • Note on the sample code: Before you give me crap about doing this in the main thread, I know. Don’t do these operation on the main thread. The example is meant to be quick and dirty and by no means is ready for production. Enjoy!

This post is part of iDevBlogADay, a group of indie iOS development blogs featuring two posts per day. You can keep up with iDevBlogADay through the web site, RSS feed, or Twitter.

[Pi]mp Wallpaper

Found on Reddit