Joystick in HUD layer - joystick

I want to give the image a joystick to HUD.
The HUD file I have:
 
myJoystick = [CCJoyStick initWithBallRadius: 25 MoveAreaRadius: 65 isFollowTouch: NO isCanVisible: YES isAutoHide: NO hasAnimation: YES];
         [myJoystick setBallTexture: # "joystick_control.png"];
         [myJoystick setDockTexture: # "joystick_lid.png"];
         [myJoystick setHitAreaWithRadius: 100];
        
         myJoystick.position = ccp (100,100);
         myJoystick.scale = 0.3;
         myJoystick.delegate = self;
         [self addChild: myJoystick of: 5];
and in HelloWorldLayer:
(Void) onCCJoyStickUpdate (CCNode *) sender Angle: (float) Angle Direction: (CGPoint) direction Power: (float) power {
     if (sender == myJoystick) {
         spider2.rotation =-angle;
...
myJoystick not found.
How do I fix this?
This is my code:
Link

Related

How to make the clicks from one UIViewController pass into the parent UIViewController through the hole

I have UIViewController (OverlayViewController), which overlay another UIViewController(RootViewController).
In OverlayViewController I add UIView for all frame size:
var overlayView = new UIView(OverlayViewController.View.Frame);
overlayView.Alpha = 0.5f;
overlayView.BackgroundColor = UIColor.Blue;
overlayView.UserInteractionEnabled = false;
View.AddSubview(overlayView);
Then I make a hole:
var path = new CGPath();
var radius = 50.0f;
var xOffset = 100;
var yOffset = 300;
path.AddArc(overlayView.Frame.Width - radius / 2 - xOffset, yOffset, radius, 0.0f, (nfloat) (2 * 3.14), false);
var cgRect = new CGRect(0, 0, overlayView.Frame.Width, overlayView.Frame.Height);
path.AddRect(cgRect);
maskLayer.BackgroundColor = UIColor.Black.CGColor;
maskLayer.Path = path;
maskLayer.FillRule = CAShapeLayer.FillRuleEvenOdd;
overlayView.Layer.Mask = maskLayer;
overlayView.ClipsToBounds = true;
When I set overlayView.UserInteractionEnabled = false; I could touch through OverlayViewController and all clicks worked.
How I can properly use UITapGestureRecognizer so that clicks by items on the RootViewController work only inside the circle? And all the other clicks were blocked.
I tried set overlayView.UserInteractionEnabled = true;, but it doesn't help me:
tap.ShouldReceiveTouch += (recognizer, touch) =>
{
return !path.ContainsPoint(touch.LocationInView(overlayView), true);
};
View.AddGestureRecognizer(tap);
I use Xamarin, but I can understand the decision on Swift too.
I found the solution...
I make custom UIView which can set CGPath.
public class OverlayView : UIView
{
public OverlayView(CGRect frame): base(frame)
{}
private CGPath _path;
public override bool PointInside(CGPoint point, UIEvent uievent)
{
return _path.ContainsPoint(point, true);
}
public void SetPoint(CGPath path)
{
_path = path;
}
}
And set overlayView.SetPoint(path);.
In OverlayView I override PointInside and check my touch points. Also, I set overlayView.UserInteractionEnabled = true;.

Add items in collection view when scrolled in Xamarin IOS

I want to add new items to collection view when user scrolled the view.
I am able to add the items successful, but the scroll bar moved to top.
Please find my below code.
ViewControll Code:
public partial class ViewController : UIViewController
{
UIWindow window;
UICollectionViewController simpleCollectionViewController;
UICollectionViewFlowLayout flowLayout;
UIScrollView viewColle = new UIScrollView( new CGRect(0,100,UIScreen.MainScreen.Bounds.Width, 500));
int count = 2;
protected ViewController(IntPtr handle) : base(handle)
{
// Note: this .ctor should not contain any initialization logic.
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
viewColle.BackgroundColor = UIColor.Green;
// Perform any additional setup after loading the view, typically from a nib.
// Flow Layout
flowLayout = new UICollectionViewFlowLayout () {
HeaderReferenceSize = new CGSize (0, 0),
SectionInset = new UIEdgeInsets (0, 0, 0, 0),
ScrollDirection = UICollectionViewScrollDirection.Vertical,
MinimumInteritemSpacing = 5, // minimum spacing between cells
MinimumLineSpacing = 5 // minimum spacing between rows if ScrollDirection is Vertical or between columns if Horizontal
};
simpleCollectionViewController = new MyCollectionViewController (flowLayout,count);
simpleCollectionViewController.CollectionView.ContentInset = new UIEdgeInsets (0, 0, 0, 0);
UIButton btnClick = new UIButton()
{
Frame = new CoreGraphics.CGRect(0,0,UIScreen.MainScreen.Bounds.Width,50),
BackgroundColor = UIColor.Gray
};
btnClick.SetTitle("Click", UIControlState.Normal);
btnClick.TouchUpInside += (sender, e) => {
window = new UIWindow(UIScreen.MainScreen.Bounds);
count++;
//var nav = new UINavigationController(simpleCollectionViewController);
//window.RootViewController = nav;
//window.MakeKeyAndVisible();
if (count > 3)
count = count / 3;
if (count == 1)
{
simpleCollectionViewController = new ListViewController (flowLayout,count,2);
simpleCollectionViewController.CollectionView.ContentInset = new UIEdgeInsets (0, 0, 0, 0);
viewColle.AddSubview(simpleCollectionViewController.View);
}
else if (count == 2)
{
simpleCollectionViewController = new MyCollectionViewController (flowLayout,count);
simpleCollectionViewController.CollectionView.ContentInset = new UIEdgeInsets (0, 0, 0, 0);
viewColle.AddSubview(simpleCollectionViewController.View);
}
else if (count == 3)
{
simpleCollectionViewController = new DetailViewController (flowLayout,1);
simpleCollectionViewController.CollectionView.ContentInset = new UIEdgeInsets (0, 0, 0, 0);
viewColle.AddSubview(simpleCollectionViewController.View);
}
//viewColle.Frame = new CGRect(0, 100, UIScreen.MainScreen.Bounds.Width, 500);
nfloat height0 = 0;
CGRect contentRect0 = new CGRect();
foreach (UIView view in viewColle.Subviews) {
height0 += view.Bounds.Height;
}
contentRect0.Size = new CGSize(View.Bounds.Width, height0 );
viewColle.ContentSize = contentRect0.Size;
//viewColle.ContentSize = new CGSize(simpleCollectionViewController.View.Bounds.Width, 2000);
View.AddSubview(btnClick);
View.AddSubview(viewColle);
};
viewColle.AddSubview(simpleCollectionViewController.View);
//viewColle.Frame = new CGRect(0, 100, UIScreen.MainScreen.Bounds.Width, 500);
nfloat height1 = 0;
CGRect contentRect1 = new CGRect();
foreach (UIView view in viewColle.Subviews) {
height1 += view.Bounds.Height;
}
contentRect1.Size = new CGSize(View.Bounds.Width, height1 );
viewColle.ContentSize = contentRect1.Size;
CGRect contentRect = new CGRect();
foreach (UIView view in viewColle.Subviews) {
contentRect = view.Frame;
}
viewColle.ContentSize = contentRect.Size;
//viewColle.ContentSize = new CGSize(simpleCollectionViewController.View.Bounds.Width, 2000);
View.AddSubview(btnClick);
View.AddSubview(viewColle);
viewColle.Scrolled += (sender, e) => {
UIAlertView alert = new UIAlertView("Scrolled Alert", "Scroller "+ count.ToString(), null, "Cancel", null);
alert.Show();
if (count > 3)
count = count / 3;
if (count == 1)
{
simpleCollectionViewController = new ListViewController (flowLayout,count,10);
simpleCollectionViewController.CollectionView.ContentInset = new UIEdgeInsets (0, 0, 0, 0);
viewColle.AddSubview(simpleCollectionViewController.View);
}
else if (count == 2)
{
simpleCollectionViewController = new MyCollectionViewController (flowLayout,count);
simpleCollectionViewController.CollectionView.ContentInset = new UIEdgeInsets (0, 0, 0, 0);
viewColle.AddSubview(simpleCollectionViewController.View);
}
else if (count == 3)
{
simpleCollectionViewController = new DetailViewController (flowLayout,1);
simpleCollectionViewController.CollectionView.ContentInset = new UIEdgeInsets (0, 0, 0, 0);
viewColle.AddSubview(simpleCollectionViewController.View);
}
nfloat height = 0;
CGRect contentRect2 = new CGRect();
foreach (UIView view in viewColle.Subviews) {
height += view.Bounds.Height;
}
contentRect2.Size = new CGSize(View.Bounds.Width, height );
viewColle.ContentSize = contentRect2.Size;
//viewColle.Frame = new CGRect(0, 100, UIScreen.MainScreen.Bounds.Width, 500);
//viewColle.ContentSize = new CGSize(simpleCollectionViewController.View.Bounds.Width, 2000);
View.AddSubview(btnClick);
View.AddSubview(viewColle);
};
}
public override void DidReceiveMemoryWarning()
{
base.DidReceiveMemoryWarning();
// Release any cached data, images, etc that aren't in use.
}
}
ListViewController Code:
public partial class ListViewController : UICollectionViewController
{
static NSString animalCellId = new NSString ("AnimalCell");
static NSString headerId = new NSString ("Header");
List<IProduct> products;
int devideValue = 0;
public ListViewController (UICollectionViewLayout layout,int divValue, int count) : base (layout)
{
devideValue = divValue;
products = new List<IProduct> ();
for (int i = 0; i < count; i++) {
Product pr = new Product();
pr.id = i;
pr.Price = i;
products.Add (pr);
}
}
[Export ("collectionView:layout:sizeForItemAtIndexPath:")]
public virtual CGSize GetSizeForItem (UICollectionView collectionView, UICollectionViewLayout layout, NSIndexPath indexPath)
{
//For 2 items devide by 2
var width = (float)(UIScreen.MainScreen.Bounds.Width/devideValue);
return new CGSize (width - 10, 125);
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
CollectionView.RegisterClassForCell (typeof(ProductCell1), animalCellId);
CollectionView.RegisterClassForSupplementaryView (typeof(Header), UICollectionElementKindSection.Header, headerId);
UIMenuController.SharedMenuController.MenuItems = new UIMenuItem[] {
new UIMenuItem ("Add to Cart?", new Selector ("addCart"))
};
}
public override nint NumberOfSections (UICollectionView collectionView)
{
return 1;
}
public override nint GetItemsCount (UICollectionView collectionView, nint section)
{
return products.Count;
}
public override UICollectionViewCell GetCell (UICollectionView collectionView, NSIndexPath indexPath)
{
var productCell = (ProductCell1)collectionView.DequeueReusableCell (animalCellId, indexPath);
var product = products [indexPath.Row];
productCell.Image = product.Image;
productCell.Price = product.Price;
productCell.Product = product.ProductName;
return productCell;
}
public override UICollectionReusableView GetViewForSupplementaryElement (UICollectionView collectionView, NSString elementKind, NSIndexPath indexPath)
{
var headerView = (Header)collectionView.DequeueReusableSupplementaryView (elementKind, headerId, indexPath);
//headerView.Text = "Product View";
//headerView.btnText = "Click";
return headerView;
}
public override void ItemHighlighted (UICollectionView collectionView, NSIndexPath indexPath)
{
var cell = collectionView.CellForItem (indexPath);
cell.ContentView.BackgroundColor = UIColor.Red;
}
public override void ItemUnhighlighted (UICollectionView collectionView, NSIndexPath indexPath)
{
var cell = collectionView.CellForItem (indexPath);
cell.ContentView.BackgroundColor = UIColor.Green;
ProductCell1 productCell = (ProductCell1)collectionView.DequeueReusableCell (animalCellId, indexPath);
int itemIndex = (int)indexPath.Item;
Product prodt = new Product();
for (int i = 0; i < products.Count; i++)
{
if (indexPath.Item == i)
{
prodt = (Product)products[i];
break;
}
}
UIAlertView alert = new UIAlertView("Selected Item", prodt.id.ToString(), null, "Cancel", null);
alert.Show();
}
//public override void ItemSelected(UICollectionView collectionView, NSIndexPath indexPath)
//{
// //var cell = collectionView.CellForItem (indexPath);
// base.ItemSelected(collectionView, indexPath);
//}
public override bool ShouldHighlightItem (UICollectionView collectionView, NSIndexPath indexPath)
{
return true;
}
// for edit menu
public override bool ShouldShowMenu (UICollectionView collectionView, NSIndexPath indexPath)
{
return true;
}
public override bool CanPerformAction (UICollectionView collectionView, Selector action, NSIndexPath indexPath, NSObject sender)
{
// Selector should be the same as what's in the AddCart UIMenuItem
if (action == new Selector ("addCart"))
return true;
else
return false;
}
public override void PerformAction (UICollectionView collectionView, Selector action, NSIndexPath indexPath, NSObject sender)
{
System.Diagnostics.Debug.WriteLine ("code to perform action");
}
// CanBecomeFirstResponder and CanPerform are needed for a AddCart menu item to appear
public override bool CanBecomeFirstResponder {
get {
return true;
}
}
}
public class ProductCell1 : UICollectionViewCell
{
UIImageView imageView;
UILabel productName;
UILabel manufacturer;
UIView cellViewContainer;
UILabel price;
[Export ("initWithFrame:")]
public ProductCell1 (CGRect frame) : base (frame)
{
BackgroundView = new UIView{ BackgroundColor = UIColor.DarkGray };
SelectedBackgroundView = new UIView{ BackgroundColor = UIColor.Green };
ContentView.Layer.BorderColor = UIColor.LightGray.CGColor;
ContentView.Layer.BorderWidth = 2.0f;
ContentView.BackgroundColor = UIColor.Gray;
cellViewContainer = new UIView ();
cellViewContainer.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
imageView = new UIImageView (UIImage.FromBundle ("placeholder.png"));
productName = new UILabel {
Text = "Name",
TextColor = UIColor.Black,
BackgroundColor = UIColor.White,
TextAlignment = UITextAlignment.Left
};
manufacturer = new UILabel {
Text = "Price",
TextColor = UIColor.Black,
BackgroundColor = UIColor.Red,
TextAlignment = UITextAlignment.Left
};
price = new UILabel {
Text = "Price",
TextColor = UIColor.Black,
BackgroundColor = UIColor.Red,
TextAlignment = UITextAlignment.Left
};
//productName.Frame = new CGRect (5, 5, labelWidth, labelHeight);
//price.Frame = new CGRect (5, labelHeight, labelWidth, labelHeight);
//imageView.Frame = new CGRect (labelWidth, 0, labelWidth, ContentView.Bounds.Height - 2);
imageView.Frame = new CGRect (3,3, ContentView.Bounds.Width/2, ContentView.Bounds.Height-3);
productName.Frame = new CGRect (ContentView.Bounds.Width/2 + 5, 3, ContentView.Bounds.Width/2 - 5, 20);
manufacturer.Frame = new CGRect (ContentView.Bounds.Width/2 + 5, 23, ContentView.Bounds.Width/2 - 5, 20);
price.Frame = new CGRect (ContentView.Bounds.Width/2 + 5, 43, ContentView.Bounds.Width/2 - 5, 20);
ContentView.AddSubviews (new UIView[] { imageView, productName, manufacturer, price });
}
public void UpdateCell ()
{
productName.Frame = new CGRect (10, 10, ContentView.Bounds.Width / 2, ContentView.Bounds.Height / 3);
price.Frame = new CGRect (20, 20, ContentView.Bounds.Width / 2, ContentView.Bounds.Height / 3);
}
public UIImage Image {
set {
imageView.Image = value;
}
}
public string Product {
set {
productName.Text = value;
}
}
public double Price {
set {
price.Text = value.ToString ("$0.00");
}
}
[Export ("addCart")]
void AddCart ()
{
// Put all your addCart menu behavior code here
Console.WriteLine ("addCart in the cell");
}
public override bool CanPerform (Selector action, NSObject withSender)
{
if (action == new Selector ("addCart"))
return true;
else
return false;
}
}
after adding the items to view the scroll bar moves to top. Please can any one suggest me to solve this.

Separate Effects Superpowered

I'm working with the SuperpoweredSDK. The SDK comes with an example called SuperpoweredCrossExample which shows off a few of the DJ-esque features. I'm trying to modify it to allow fx (such as filters, rolls, and flanger) to be applied to one player at a time instead of both simultaneously.
I've attempted in the code below to have a different buffer for each player and then merge them using the SuperpoweredStereoMixer. Although this seems to work for many others in sample code I've found, for me it continues to to crash on the "mixer" line. Any help would be very much appreciated. I've been spinning on this for the last few weeks.
#import "ViewController.h"
#import "SuperpoweredAdvancedAudioPlayer.h"
#import "SuperpoweredFilter.h"
#import "SuperpoweredRoll.h"
#import "SuperpoweredFlanger.h"
#import "SuperpoweredIOSAudioIO.h"
#import "SuperpoweredSimple.h"
#import "SuperpoweredMixer.h"
#import <stdlib.h>
#import <pthread.h>
#define HEADROOM_DECIBEL 3.0f
static const float headroom = powf(10.0f, -HEADROOM_DECIBEL * 0.025);
/*
This is a .mm file, meaning it's Objective-C++.
You can perfectly mix it with Objective-C or Swift, until you keep the member variables and C++ related includes here.
Yes, the header file (.h) isn't the only place for member variables.
*/
#implementation ViewController {
SuperpoweredAdvancedAudioPlayer *playerA, *playerB;
SuperpoweredIOSAudioIO *output;
SuperpoweredRoll *roll;
SuperpoweredFilter *filter;
SuperpoweredFlanger *flanger;
SuperpoweredStereoMixer *mixer;
unsigned char activeFx;
float *stereoBufferA, *stereoBufferB, crossValue, volA, volB;
unsigned int lastSamplerate;
pthread_mutex_t mutex;
}
void playerEventCallbackA(void *clientData, SuperpoweredAdvancedAudioPlayerEvent event, void *value) {
if (event == SuperpoweredAdvancedAudioPlayerEvent_LoadSuccess) {
ViewController *self = (__bridge ViewController *)clientData;
self->playerA->setBpm(126.0f);
self->playerA->setFirstBeatMs(353);
self->playerA->setPosition(self->playerA->firstBeatMs, false, false);
};
}
void playerEventCallbackB(void *clientData, SuperpoweredAdvancedAudioPlayerEvent event, void *value) {
if (event == SuperpoweredAdvancedAudioPlayerEvent_LoadSuccess) {
ViewController *self = (__bridge ViewController *)clientData;
self->playerB->setBpm(123.0f);
self->playerB->setFirstBeatMs(40);
self->playerB->setPosition(self->playerB->firstBeatMs, false, false);
};
}
- (void)viewDidLoad {
[super viewDidLoad];
lastSamplerate = activeFx = 0;
crossValue = volB = 0.0f;
volA = 1.0f * headroom;
pthread_mutex_init(&mutex, NULL); // This will keep our player volumes and playback states in sync.
if (posix_memalign((void **)&stereoBufferA, 16, 4096 + 128) != 0) abort(); // Allocating memory, aligned to 16.
if (posix_memalign((void **)&stereoBufferB, 16, 4096 + 128) != 0) abort(); // Allocating memory, aligned to 16.
playerA = new SuperpoweredAdvancedAudioPlayer((__bridge void *)self, playerEventCallbackA, 44100, 0);
playerA->open([[[NSBundle mainBundle] pathForResource:#"lycka" ofType:#"mp3"] fileSystemRepresentation]);
playerB = new SuperpoweredAdvancedAudioPlayer((__bridge void *)self, playerEventCallbackB, 44100, 0);
playerB->open([[[NSBundle mainBundle] pathForResource:#"nuyorica" ofType:#"m4a"] fileSystemRepresentation]);
playerA->syncMode = playerB->syncMode = SuperpoweredAdvancedAudioPlayerSyncMode_TempoAndBeat;
roll = new SuperpoweredRoll(44100);
filter = new SuperpoweredFilter(SuperpoweredFilter_Resonant_Lowpass, 44100);
flanger = new SuperpoweredFlanger(44100);
output = [[SuperpoweredIOSAudioIO alloc] initWithDelegate:(id<SuperpoweredIOSAudioIODelegate>)self preferredBufferSize:12 preferredMinimumSamplerate:44100 audioSessionCategory:AVAudioSessionCategoryPlayback channels:2];
[output start];
}
- (void)dealloc {
delete playerA;
delete playerB;
free(stereoBufferA);
free(stereoBufferB);
pthread_mutex_destroy(&mutex);
#if !__has_feature(objc_arc)
[output release];
[super dealloc];
#endif
}
- (void)interruptionStarted {}
- (void)recordPermissionRefused {}
- (void)interruptionEnded { // If a player plays Apple Lossless audio files, then we need this. Otherwise unnecessary.
playerA->onMediaserverInterrupt();
playerB->onMediaserverInterrupt();
}
// This is where the Superpowered magic happens.
- (bool)audioProcessingCallback:(float **)buffers inputChannels:(unsigned int)inputChannels outputChannels:(unsigned int)outputChannels numberOfSamples:(unsigned int)numberOfSamples samplerate:(unsigned int)samplerate hostTime:(UInt64)hostTime {
if (samplerate != lastSamplerate) { // Has samplerate changed?
lastSamplerate = samplerate;
playerA->setSamplerate(samplerate);
playerB->setSamplerate(samplerate);
roll->setSamplerate(samplerate);
filter->setSamplerate(samplerate);
flanger->setSamplerate(samplerate);
};
pthread_mutex_lock(&mutex);
bool masterIsA = (crossValue <= 0.5f);
float masterBpm = masterIsA ? playerA->currentBpm : playerB->currentBpm; // Players will sync to this tempo.
double msElapsedSinceLastBeatA = playerA->msElapsedSinceLastBeat; // When playerB needs it, playerA has already stepped this value, so save it now.
bool silence = !playerA->process(stereoBufferA, false, numberOfSamples, volA, masterBpm, playerB->msElapsedSinceLastBeat);
if (playerB->process(stereoBufferB, !silence, numberOfSamples, volB, masterBpm, msElapsedSinceLastBeatA)) silence = false;
roll->bpm = flanger->bpm = masterBpm; // Syncing fx is one line.
if (roll->process(silence ? NULL : stereoBufferA, stereoBufferA, numberOfSamples) && silence) silence = false;
if (!silence) {
filter->process(stereoBufferB, stereoBufferB, numberOfSamples);
flanger->process(stereoBufferB, stereoBufferB, numberOfSamples);
};
pthread_mutex_unlock(&mutex);
float *mixerInputs[4] = { stereoBufferA, stereoBufferB, NULL, NULL };
float mixerInputLevels[8] = { 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f };
float mixerOutputLevels[2] = { 1.0f, 1.0f };
if (!silence) mixer->process(mixerInputs, buffers, mixerInputLevels, mixerOutputLevels, NULL, NULL, numberOfSamples);
/*if (!silence) SuperpoweredDeInterleave(stereoBuffer, buffers[0], buffers[1], numberOfSamples); // The stereoBuffer is ready now, let's put the finished audio into the requested buffers.*/
return !silence;
}
- (IBAction)onPlayPause:(id)sender {
UIButton *button = (UIButton *)sender;
pthread_mutex_lock(&mutex);
if (playerA->playing) {
playerA->pause();
playerB->pause();
} else {
bool masterIsA = (crossValue <= 0.5f);
playerA->play(!masterIsA);
playerB->play(masterIsA);
};
pthread_mutex_unlock(&mutex);
button.selected = playerA->playing;
}
- (IBAction)onCrossFader:(id)sender {
pthread_mutex_lock(&mutex);
crossValue = ((UISlider *)sender).value;
if (crossValue < 0.01f) {
volA = 1.0f * headroom;
volB = 0.0f;
} else if (crossValue > 0.99f) {
volA = 0.0f;
volB = 1.0f * headroom;
} else { // constant power curve
volA = cosf(M_PI_2 * crossValue) * headroom;
volB = cosf(M_PI_2 * (1.0f - crossValue)) * headroom;
};
pthread_mutex_unlock(&mutex);
}
static inline float floatToFrequency(float value) {
static const float min = logf(20.0f) / logf(10.0f);
static const float max = logf(20000.0f) / logf(10.0f);
static const float range = max - min;
return powf(10.0f, value * range + min);
}
- (IBAction)onFxSelect:(id)sender {
activeFx = ((UISegmentedControl *)sender).selectedSegmentIndex;
}
- (IBAction)onFxValue:(id)sender {
float value = ((UISlider *)sender).value;
switch (activeFx) {
case 1:
filter->setResonantParameters(floatToFrequency(1.0f - value), 0.1f);
filter->enable(true);
flanger->enable(false);
roll->enable(false);
break;
case 2:
if (value > 0.8f) roll->beats = 0.0625f;
else if (value > 0.6f) roll->beats = 0.125f;
else if (value > 0.4f) roll->beats = 0.25f;
else if (value > 0.2f) roll->beats = 0.5f;
else roll->beats = 1.0f;
roll->enable(true);
filter->enable(false);
flanger->enable(false);
break;
default:
flanger->setWet(value);
flanger->enable(true);
filter->enable(false);
roll->enable(false);
};
}
- (IBAction)onFxOff:(id)sender {
filter->enable(false);
roll->enable(false);
flanger->enable(false);
}
#end

Draw into UIImage

how can I draw into an existing UIImage using monotouch?
I load an image: UIImage.FromFile("MyImage.png")
Then I want to draw a string and some lines into this image.
Does anyone has a code sample?
Thx
Here is a method that does it:
private void drawOnTouch(object data)
{
UITouch touch = data as UITouch;
if (null != touch)
{
UIGraphics.BeginImageContext(this.Image == null ? this.Frame.Size : this.Image.Size);
using (CGContext cont = UIGraphics.GetCurrentContext())
{
if (this.Image != null)
{
cont.TranslateCTM(0f, this.Image.Size.Height);
cont.ScaleCTM(1.0f, -1.0f);
cont.DrawImage(new RectangleF(0f,0f,this.Image.Size.Width, this.Image.Size.Height), this.Image.CGImage);
cont.ScaleCTM(1.0f, -1.0f);
cont.TranslateCTM(0f, -this.Image.Size.Height);
} //end if
PointF lastLocation = touch.PreviousLocationInView(this);
PointF pt = touch.LocationInView(this);
using (CGPath path = new CGPath())
{
cont.SetLineCap(CGLineCap.Round);
cont.SetLineWidth(3);
cont.SetRGBStrokeColor(0, 2, 3, 1);
path.MoveToPoint(lastLocation.X, lastLocation.Y);
path.AddLines(new PointF[] { new PointF(lastLocation.X,
lastLocation.Y),
new PointF(pt.X, pt.Y) });
path.CloseSubpath();
cont.AddPath(path);
cont.DrawPath(CGPathDrawingMode.FillStroke);
this.Image = UIGraphics.GetImageFromCurrentImageContext();
}//end using path
}//end using cont
UIGraphics.EndImageContext();
this.SetNeedsDisplay();
}//end if
}//end void drawOnTouch
If you place this method in a subclass of UIImageView and call it from TouchesBegan and TouchesMoved, when you touch the screen it will draw on the image.

UIImagePickerController returning incorrect image orientation

I'm using UIImagePickerController to capture an image and then store it. However, when i try to rescale it, the orientation value i get out of this image is incorrect. When i take a snap by holding the phone Up, it gives me orientation of Left. Has anyone experienced this issue?
The UIImagePickerController dictionary shows following information:
{
UIImagePickerControllerMediaMetadata = {
DPIHeight = 72;
DPIWidth = 72;
Orientation = 3;
"{Exif}" = {
ApertureValue = "2.970853654340484";
ColorSpace = 1;
DateTimeDigitized = "2011:02:14 10:26:17";
DateTimeOriginal = "2011:02:14 10:26:17";
ExposureMode = 0;
ExposureProgram = 2;
ExposureTime = "0.06666666666666667";
FNumber = "2.8";
Flash = 32;
FocalLength = "3.85";
ISOSpeedRatings = (
125
);
MeteringMode = 1;
PixelXDimension = 2048;
PixelYDimension = 1536;
SceneType = 1;
SensingMethod = 2;
Sharpness = 1;
ShutterSpeedValue = "3.910431673351467";
SubjectArea = (
1023,
767,
614,
614
);
WhiteBalance = 0;
};
"{TIFF}" = {
DateTime = "2011:02:14 10:26:17";
Make = Apple;
Model = "iPhone 3GS";
Software = "4.2.1";
XResolution = 72;
YResolution = 72;
};
};
UIImagePickerControllerMediaType = "public.image";
UIImagePickerControllerOriginalImage = "<UIImage: 0x40efb50>";
}
However picture returns imageOrientation == 1;
UIImage *picture = [info objectForKey:UIImagePickerControllerOriginalImage];
I just started working on this issue in my own app.
I used the UIImage category that Trevor Harmon crafted for resizing an image and fixing its orientation, UIImage+Resize.
Then you can do something like this in -imagePickerController:didFinishPickingMediaWithInfo:
UIImage *pickedImage = [info objectForKey:UIImagePickerControllerEditedImage];
UIImage *resized = [pickedImage resizedImageWithContentMode:UIViewContentModeScaleAspectFit bounds:pickedImage.size interpolationQuality:kCGInterpolationHigh];
This fixed the problem for me. The resized image is oriented correctly visually and the imageOrientation property reports UIImageOrientationUp.
There are several versions of this scale/resize/crop code out there; I used Trevor's because it seems pretty clean and includes some other UIImage manipulators that I want to use later.
This what I have found for fixing orientation issue; Works for me
UIImage *initialImage = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
NSData *data = UIImagePNGRepresentation(self.initialImage);
UIImage *tempImage = [UIImage imageWithData:data];
UIImage *fixedOrientationImage = [UIImage imageWithCGImage:tempImage.CGImage
scale:initialImage.scale
orientation:self.initialImage.imageOrientation];
initialImage = fixedOrientationImage;
Here's a Swift snippet that fixes the problem efficiently:
let orientedImage = UIImage(CGImage: initialImage.CGImage, scale: 1, orientation: initialImage.imageOrientation)!
I use the following code that I have put in a separate image utility object file that has a bunch of other editing methods for UIImages:
+ (UIImage*)imageWithImage:(UIImage*)sourceImage scaledToSizeWithSameAspectRatio:(CGSize)targetSize
{
CGSize imageSize = sourceImage.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;
CGFloat targetWidth = targetSize.width;
CGFloat targetHeight = targetSize.height;
CGFloat scaleFactor = 0.0;
CGFloat scaledWidth = targetWidth;
CGFloat scaledHeight = targetHeight;
CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
if (CGSizeEqualToSize(imageSize, targetSize) == NO) {
CGFloat widthFactor = targetWidth / width;
CGFloat heightFactor = targetHeight / height;
if (widthFactor > heightFactor) {
scaleFactor = widthFactor; // scale to fit height
}
else {
scaleFactor = heightFactor; // scale to fit width
}
scaledWidth = width * scaleFactor;
scaledHeight = height * scaleFactor;
// center the image
if (widthFactor > heightFactor) {
thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
}
else if (widthFactor < heightFactor) {
thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
}
}
CGImageRef imageRef = [sourceImage CGImage];
CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
CGColorSpaceRef colorSpaceInfo = CGImageGetColorSpace(imageRef);
if (bitmapInfo == kCGImageAlphaNone) {
bitmapInfo = kCGImageAlphaNoneSkipLast;
}
CGContextRef bitmap;
if (sourceImage.imageOrientation == UIImageOrientationUp || sourceImage.imageOrientation == UIImageOrientationDown) {
bitmap = CGBitmapContextCreate(NULL, targetWidth, targetHeight, CGImageGetBitsPerComponent(imageRef), CGImageGetBytesPerRow(imageRef), colorSpaceInfo, bitmapInfo);
} else {
bitmap = CGBitmapContextCreate(NULL, targetHeight, targetWidth, CGImageGetBitsPerComponent(imageRef), CGImageGetBytesPerRow(imageRef), colorSpaceInfo, bitmapInfo);
}
// In the right or left cases, we need to switch scaledWidth and scaledHeight,
// and also the thumbnail point
if (sourceImage.imageOrientation == UIImageOrientationLeft) {
thumbnailPoint = CGPointMake(thumbnailPoint.y, thumbnailPoint.x);
CGFloat oldScaledWidth = scaledWidth;
scaledWidth = scaledHeight;
scaledHeight = oldScaledWidth;
CGContextRotateCTM (bitmap, M_PI_2); // + 90 degrees
CGContextTranslateCTM (bitmap, 0, -targetHeight);
} else if (sourceImage.imageOrientation == UIImageOrientationRight) {
thumbnailPoint = CGPointMake(thumbnailPoint.y, thumbnailPoint.x);
CGFloat oldScaledWidth = scaledWidth;
scaledWidth = scaledHeight;
scaledHeight = oldScaledWidth;
CGContextRotateCTM (bitmap, -M_PI_2); // - 90 degrees
CGContextTranslateCTM (bitmap, -targetWidth, 0);
} else if (sourceImage.imageOrientation == UIImageOrientationUp) {
// NOTHING
} else if (sourceImage.imageOrientation == UIImageOrientationDown) {
CGContextTranslateCTM (bitmap, targetWidth, targetHeight);
CGContextRotateCTM (bitmap, -M_PI); // - 180 degrees
}
CGContextDrawImage(bitmap, CGRectMake(thumbnailPoint.x, thumbnailPoint.y, scaledWidth, scaledHeight), imageRef);
CGImageRef ref = CGBitmapContextCreateImage(bitmap);
UIImage* newImage = [UIImage imageWithCGImage:ref];
CGContextRelease(bitmap);
CGImageRelease(ref);
return newImage;
}
And then I call
UIImage *pickedImage = [info objectForKey:UIImagePickerControllerOriginalImage];
UIImage *fixedOriginal = [ImageUtil imageWithImage:[mediaInfoDict objectForKey:UIImagePickerControllerOriginalImage] scaledToSizeWithSameAspectRatio:pickedImage.size];
In iOS 7, I needed code dependent on UIImage.imageOrientation to correct for the different orientations. Now, in iOS 8.2, when I pick my old test images from the album via UIImagePickerController, the orientation will be UIImageOrientationUp for ALL images. When I take a photo (UIImagePickerControllerSourceTypeCamera), those images will also always be upwards, regardless of the device orientation.
So between those iOS versions, there obviously has been a fix where UIImagePickerController already rotates the images if neccessary.
You can even notice that when the album images are displayed: for a split second, they will be displayed in the original orientation, before they appear in the new upward orientation.
The only thing that worked for me was to re-render the image again which forces the correct orientation.
if (photo.imageOrientation != .up) {
UIGraphicsBeginImageContextWithOptions(photo.size, false, 1.0);
let rect = CGRect(x: 0, y: 0, width: photo.size.width, height: photo.size.height);
photo.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
photo = newImage;
}

Resources