Question: is it legal to castle out of check

Answer: No, Castling consists of moving the king two squares towards a rook on the player's first rank , then moving the rook to the square over which the king crossed. Castling may only be done if the king has never moved, the rook involved has never moved, the squares between the king and the rook involved are unoccupied, the king is not in check, and the king does not cross over or end on a square in which it would be in check. Castling is one of the rules of chess and is technically a king move (Hooper & Whyld 1992:71).